A best time, buying and selling stocks array --- 2

Given an array, which i-th element is a given stock i-day prices.

Design an algorithm to compute the maximum profit you can get. You can close more deals (buy and sell a stock) as much as possible.

Note: You can not simultaneously involved in multiple transactions (you must sell before buying shares again before the fall).

Example 1:

Input: [7,1,5,3,6,4]
Output: 7
Explanation: Day 2 (= 1 stock price), when buying, on day 3 (stock price = 5) when sold, this transaction can profit = 5-1 = 4.
  Then, on day 4 (stock price = 3) When buying on day 5 (stock price = 6), when sold, this transaction can profit = 6-3 = 3.
Example 2:

Enter: [1,2,3,4,5]
Output: 4
to explain: (stock price = 1) when buying on Day 1, on Day 5 (stock price = 5), when sold, this Exchange can profit = 5-1 = 4.
  Note that you can not buy stock in a series of 1 and day 2, then after they are sold.
  Because it belongs to the same time involved in multiple transactions, you have to sell the stock before the fall before buying again.
Example 3:

Enter: [7,6,4,3,1]
Output: 0
to explain: In this case, no transaction is completed, the maximum profit is zero.

 

method

Algorithm can be simplified as directly as long as large today than yesterday, calculates maxprofit.

There are two cases: (1) Change down up; (2) low high, the last to sell; (3) the level of ~ ~, the first time to buy low;

 

1  // calculated from the perspective of benefits 
2  class Solution {
 . 3  public :
 . 4      int MAXPROFIT (Vector < int > & Prices) {
 . 5          int MAXPROFIT = 0 ;
 . 6          // Each loop is looking for a cell room, to find to find the i ++ the next interval 
. 7          for ( int I = . 1 ; I <prices.size (); I ++ ) {
 . 8              // I = 0 line cycle begins, but price.size () returns the unsigned type, price.size () - 1 is a substantially infinite 
. 9              IF (Prices [I]> Prices [I - 1 ])
 10                  MAXPROFIT + = Prices [I] - Prices [I -1];
11         }
12         return maxprofit;
13     }
14 };
1  // same idea 
2  class Solution {
 . 3  public :
 . 4      int MAXPROFIT (Vector < int > & Prices) {
 . 5          IF (prices.size () < 2 ) return  0 ;
 . 6          int I = 0 ;
 . 7          int MAXPRO = 0 ; // maximum profit 
. 8          int Valley Prices = [ 0 ]; // valley 
. 9          int peak = Prices [ 0 ]; // peak 
10         while(i<prices.size()-1)
11         {
12             while(i<prices.size()-1 && prices[i+1]<=prices[i])
13                 i++;
14             valley=prices[i];
15             while(i<prices.size()-1 && prices[i+1]>=prices[i])
16                 i++;
17             peak=prices[i];
18             maxpro+=peak-valley;
19         }
20         return maxpro;
21     }
22 };

 

Guess you like

Origin www.cnblogs.com/pacino12134/p/10993418.html