[LeetCode] 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).

方法:实现波浪线中所有上升曲线之和,所有相邻上升曲线之和总会大于不相邻上升值之和的。因为在卖了手中有的股票之前也不能再买。

 int maxProfit(vector<int> &prices) {
        if(prices.size()<2)
          return 0;
        
        int sum = 0;
        
          for(int i=0;i<prices.size()-1;i++)
             if(prices[i]<prices[i+1])
               sum += (prices[i+1]-prices[i]);
       return sum;
    }

 

posted @ 2014-06-17 12:03  Xylophone  Views(108)  Comments(0Edit  收藏  举报