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

 

这道题跟Best Time to Buy and Sell Stock类 似,求最大利润。区别是这里可以交易无限多次(当然我们知道交易不会超过n-1次,也就是每天都进行先卖然后买)。既然交易次数没有限定,可以看出我们只 要对于每次两天差价大于0的都进行交易,就可以得到最大利润。因此算法其实就是累加所有大于0的差价既可以了,非常简单。如此只需要一次扫描就可以了,时 间复杂度是O(n),空间上只需要O(1)存一个累加结果即可。代码如下: 

  1. public int maxProfit(int[] prices) {  
  2.   
  3.     if(prices == null || prices.length==0)  
  4.         return 0;  
  5.     int res = 0;  
  6.     for(int i=0;i<prices.length-1;i++)  
  7.     {  
  8.         int diff = prices[i+1]-prices[i];  
  9.         if(diff>0)  
  10.             res += diff;  
  11.     }  
  12.     return res;  
  13. }  

这道题其实比Best Time to Buy and Sell Stock更加简单,只需要看透背后的模型就很OK了哈。

 

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

 

posted on 2015-01-06 20:45  风云逸  阅读(79)  评论(0)    收藏  举报