当前位置:网站首页>2022.04.23 (the best time for lc_714_to buy and sell stocks, including handling charges)

2022.04.23 (the best time for lc_714_to buy and sell stocks, including handling charges)

2022-04-23 18:53:00 Leeli9316

  Method : greedy

class Solution {
    public int maxProfit(int[] prices, int fee) {
        int profit = 0;
        //buy It means that on the premise of maximizing benefits , The lowest purchase price of a stock 
        int buy = prices[0] + fee;
        for (int i = 1; i < prices.length; i++) {
            // If the current stock price plus handling fee is less than buy
            // It means you can buy at a lower price , to update buy
            if (prices[i] + fee < buy) {
                buy = prices[i] + fee;
            // If the current stock price is greater than buy, You can get income 
            // But actually , At this time, selling stocks may not be globally optimal ( For example, the stock price continues to rise the next day )
            } else if (prices[i] > buy) {
                profit += prices[i] - buy;
                // So will buy Updated to prices[i], If the stock price continues to rise the next day ,
                // Will get prices[i+1]−prices[i] Revenue , Add this day prices[i]−buy  Revenue ,
                // It's exactly the same as not doing anything on this day , And the return on selling shares the next day 
                buy = prices[i];
            }
        }
        return profit;
    }
}

版权声明
本文为[Leeli9316]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204231851339576.html