首页 > 代码库 > [LeetCode]122 Best Time to Buy and Sell Stock II

[LeetCode]122 Best Time to Buy and Sell Stock II

https://oj.leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/

http://blog.csdn.net/linhuanmars/article/details/23164149

public class Solution {
    
    public int maxProfit(int[] prices) {
        
        // If as many transactions 
        // Gready
        
        int pro = 0;
        int buy = 0;
        boolean hold = false;
        
        int len = prices.length;
        
        for (int i = 0 ; i < len ; i ++)
        {
            if (!hold)
            {
                // Find the next buy day
                if (i + 1 < len && prices[i + 1] > prices[i])
                {
                    buy = prices[i];
                    hold = true;
                }
            }
            else
            {
                // Find the next sell day
                if ((i == len - 1) || // Last day, sell whatever we have
                   (i + 1 < len && prices[i + 1] < prices[i])) // A good sell day.
                {
                    pro += prices[i] - buy;
                    hold = false;
                }
            }
        }
        
        return pro;
    }
}


[LeetCode]122 Best Time to Buy and Sell Stock II