[Leetcode 37] 121 Best Time to Buy and Sell Stock

Probelm:

Say you have an array for which the ith element is the price of a given stock on day i.

If you were only permitted to complete at most one transaction (ie, buy one and sell one share of the stock), design an algorithm to find the maximum profit.

Analysis:

There's obviously a O(n^2) algorithm: try every possible trading plan and find the max one. But it's too slow.

Another method is that, we first compute every profit in two consecutive days, then in this new profit array, we find the max subarray. This is what we need. Since build a profit array is O(n) and find max subarray is also O(n). The total time complexity is O(n).

Code:

 1 class Solution {
 2 public:
 3     int maxProfit(vector<int> &prices) {
 4         // Start typing your C/C++ solution below
 5         // DO NOT write int main() function
 6         if (prices.size() == 0 || prices.size() == 1) return 0;
 7 
 8         vector<int> profit;
 9         
10         for (int i=1; i<prices.size(); i++) {
11             profit.push_back( prices[i] - prices[i-1]);
12         }
13         
14         int max = profit[0], cmax = profit[0];
15         for (int i=1; i<profit.size(); i++) {
16             if (cmax < 0) {
17                cmax = profit[i];
18             } else {
19                 cmax += profit[i];
20             }
21             
22             if (cmax > max) {
23                 max = cmax;
24             }
25         }
26         
27         return max>0? max : 0;
28     }
29 };
View Code

Attention:

blabla

原文地址:https://www.cnblogs.com/freeneng/p/3096150.html