Best Time to Buy and Sell Stock II

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).

算法:所有连续单调非递减区间的利润和,连续是指这个区间的元素在数组下标中是连续的。

为什么是这样的呢?

假设有数组:a1,a2,a3,a4,a5,a6,a7,a8,a9;其中{a1,a2,a3},{a6,a7}为所有的连续单调非递减区间

也就是说:a1<=a2<=a3,a3>a4>a5>a6,a6<=a7,a7>a8>a9

我们认为最大的利益是:profit = a2-a1+a3-a2 + a7-a6 = a3-a1 + a7-a6;

也就是a1买入a3卖出,a6买入a7卖出

为什么a1买入a3卖出?

首先,肯定不会在a4,a5,a6卖出,因为a3>a4>a5>a6

也不会在a8,a9中卖出,因为a7>a8>a9;

如果在a7卖出,则有profit= a7-a1 < a3-a1+a7-a6

所以,跨区间购买并不能增加利益。

class Solution {
public:
    int maxProfit(vector<int>& prices) {
        int profit = 0;
        int pricesSize = prices.size();
        for(int i=1;i<pricesSize;i++){
            if(prices[i]>prices[i-1]){
                profit += prices[i] - prices[i-1];
            }
        }
        return profit;
    }
};

 

posted @ 2015-11-29 12:17  zengzy  阅读(137)  评论(0编辑  收藏  举报
levels of contents