1.Description
There is an array named prices. prices[i] is the price of the given stock on the ith day. Our task is to miximize the profit by choosing the day to buy and sell the stock. The day to buy and the day to sell must be different. If there is no profit, return 0.
2.Algorithms I use
two pointers
stack
dynamic programming 这里
3.analysis&code
two pointers
If I sell the stock on the ith day, I must choose the day that is before the ith day and has the lowest price as the day to buy the stock to get the greatest profit. Hence, we can use two pointers. Pointer i iteraters through the array and Pointer cmin saves the smallest element(the lowest price before day i).For element i, the greatest profit of choosing day i as the day to sell stock must be the price of day i minus cmin. Then we choose the greatest one of all elements’ profit.
class Solution {
public:
int maxProfit(vector<int>& prices) {
int cmin = 10001, ans = 0;
for(int i = 0;i<prices.size();i++){
cmin = min(cmin, prices[i]);
ans = max(ans, prices[i]-cmin);
}
return ans;
}
};
stack
The key idea of stack is the same as two pointers. The only difference is how the smallest element is stored. In two pointers, we use variable(or pointer) cmin to store the lowest price. Now we use stack to store it.
class Solution {
public:
int maxProfit(vector<int>& prices) {
stack<int> cmin;
int ans = 0, tmp = 10001;
cmin.push(tmp);
for(int i = 0;i<prices.size();i++){
if(prices[i] < cmin.top())
cmin.push(prices[i]);
else
ans = max(ans, prices[i]-cmin.top());
}
return ans;
}
};
4.Complexity
Time complexity: O(n)
Space complexity: O(1)