题目描述:

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 class Solution {
 2 public:
 3     int maxProfit(vector<int>& prices) {
 4         if(prices.size()<=1)
 5             return 0;
 6         int sum=0;
 7         for(int i=1;i<prices.size();i++){
 8             sum+=max(prices[i]-prices[i-1],0);//把递增的条件改进了一下
 9         }
10         return sum;
11     }
12 };

 

 

 

posted on 2018-02-12 15:15  宵夜在哪  阅读(90)  评论(0编辑  收藏  举报