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

110_leetcode_Best Time to Buy and sell Stock II

时间:2016-02-18 13:55:51      阅读:177      评论: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
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!