-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path121.cpp
36 lines (29 loc) · 891 Bytes
/
121.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
// 121. Best Time to Buy and Sell Stock - https://leetcode.com/problems/best-time-to-buy-and-sell-stock
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
int maxProfit(vector<int>& prices) {
Result result;
for (int price : prices) {
result.updateMinPrice(price);
result.tryToSell(price);
}
return result.maxProfitSoFar;
}
private:
struct Result {
int maxProfitSoFar, minPriceSoFar;
Result(): maxProfitSoFar(0), minPriceSoFar(INT_MAX) {};
void updateMinPrice(int currentPrice) {
minPriceSoFar = min(minPriceSoFar, currentPrice);
}
void tryToSell(int currentPrice) {
maxProfitSoFar = max(maxProfitSoFar, currentPrice - minPriceSoFar);
}
};
};
int main() {
ios::sync_with_stdio(false);
return 0;
}