Given an array, which i-th element is a given stock i-day prices.
If you are only allowed up to complete a transaction (ie buying and selling a stock), to design an algorithm to compute the maximum profit you can get.
Note that you can not sell the stock before buying stocks.
Example 1:
Input: [7,1,5,3,6,4]
Output: 5
Explanation: Day 2 (= 1 stock price), when buying, on day 5 (stock price = 6), when sold, The maximum profit = 6-1 = 5.
Note that profits can not be 7-1 = 6, because the selling price must be greater than the purchase price.
Example 2:
Enter: [7,6,4,3,1]
Output: 0
to explain: In this case, no transaction is completed, the maximum profit is zero.
Method a: two traverse
Time and space consumption! !
1 class Solution { 2 public: 3 int maxProfit(vector<int>& prices) { 4 int max_value = 0; 5 int res; 6 if(prices.size()<=1) return 0; 7 for(int i=prices.size() - 1;i>=0;i--){ 8 for(int j=i-1;j>=0;j--){ 9 res = prices[i] - prices[j]; 10 if(res > max_value) max_value = res; 11 } 12 } 13 return max_value; 14 } 15 };
Method two: into sequences and a maximum seek
1 class Solution { 2 public: 3 int maxProfit(vector<int>& prices) { 4 vector<int> trend; 5 if (prices.size() < 2) 6 { 7 return 0; 8 } 9 for (int i = 0; i < prices.size() - 1; i++) 10 { 11 trend.push_back(prices[i+1] - Prices [I]); // The daily stock price ups and downs of the stock configuration array 12 is } 13 is 14 int SUM = 0 ; 15 int max = Trend [ 0 ]; 16 for ( int I = 0 ; I <Trend. size (); I ++) // maximum Change subarray arrays and calculating . 17 { 18 is SUM = SUM> 0 SUM +? Trend [I]: Trend [I]; . 19 ? max = max> SUM max: SUM; 20 is } 21 is max = max < 0 ? 0 : max; 22 return max; 23 } 24 };