码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2015-01-06 18:13:23      阅读:132      评论:0      收藏:0      [点我收藏+]

标签:leetcode

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

标签:leetcode

原文地址:http://7371901.blog.51cto.com/7361901/1599879

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!