[LeetCode] Best Time to Buy and Sell Stock

121. Best Time to Buy and Sell Stock

You are given an array prices where prices[i] is the price of a given stock on the ith day.

You want to maximize your profit by choosing a single day to buy one stock and choosing a different day in the future to sell that stock.

Return the maximum profit you can achieve from this transaction. If you cannot achieve any profit, return 0.

  • new solution update 2022.02.07
1
2
3
4
5
6
7
8
9
10
11
12
class Solution {
public:
int maxProfit(vector<int>& prices) {
int res = 0, st = INT_MAX;
for(auto& n : prices) {
st = min(st, n);
res = max(res , n - st);
}
return res;
}
};

1
2
3
4
5
6
7
8
9
10
11
12
class Solution {
public:
int maxProfit(vector<int>& prices) {
int res = 0, price = 0;
for(int i = prices.size() - 1; i >= 0; i--) {
res = max(res, price - prices[i]);
price = max(price, prices[i]);
}

return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/02/01/PS/LeetCode/best-time-to-buy-and-sell-stock/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.