首页 > 其他 > 详细

110_leetcode_Best Time to Buy and sell Stock II

时间:2016-02-18 13:53:26      阅读:125      评论:0      收藏:0      [点我收藏+]

Say you have an array for which the ith element is the price of a given stock on day i.

Design an algorithm to find the maximum profit. You may complete as many transactions as you like (ie, buy one and sell one share of the stock multiple times). However, you may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).


1:注意特殊情况;2:找到数组相邻的凹点和凸点;3:两者的差值是当前的最大值。4:在查找凸凹值的时候注意边界


    int maxProfit(vector<int> &prices)
    {
        if(prices.size() <= 1)
        {
            return 0;
        }
        
        int maxValue = 0;
        int start = 0;
        int end = 0;
        int size = (int)prices.size();
        
        while(start < size)
        {
            while(start < size - 1 && prices[start] >= prices[start + 1])
            {
                start++;
            }
            
            end = start + 1;
            while(end < size - 1 && prices[end] <= prices[end + 1])
            {
                end++;
            }
            
            if(end == size)
            {
                break;
            }
            else
            {
                maxValue += prices[end] - prices[start];
            }
            
            start = end + 1;
        }
        
        
        return maxValue;
    }


110_leetcode_Best Time to Buy and sell Stock II

原文:http://www.cnblogs.com/gcczhongduan/p/5197858.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!