首页 > 代码库 > Best Time to Buy and Sell Stock II

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

思路:因为可以进行任意多次的交易,所以只需将所有递增区间增量相加即可。

 1 class Solution { 2 public: 3     int maxProfit( vector<int> &prices ) { 4         if( prices.empty() ) { return 0; } 5         int curMin = prices[0], profit = 0; 6         int i = 0, size = prices.size(); 7         while( ++i < size ) { 8             if( prices[i] <= prices[i-1] ) { continue; } 9             curMin = prices[i-1];10             while( i < size && prices[i] > prices[i-1] ) { ++i; }11             profit += prices[i-1] - curMin;12         }13         return profit;14     }15 };

下面是网上看到的更加简洁的实现:

 1 class Solution { 2 public: 3     int maxProfit( vector<int> &prices ) { 4         if( prices.empty() ) { return 0; } 5         int profit = 0; 6         for( size_t i = 1; i != prices.size(); ++i ) { 7             if( prices[i] > prices[i-1] ) { profit += prices[i] - prices[i-1]; } 8         } 9         return profit;10     }11 };