forked from USPCodeLabSanca/dev.hire-2021
-
Notifications
You must be signed in to change notification settings - Fork 0
/
121.cpp
34 lines (27 loc) · 945 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
class Solution {
public:
int maxProfit(vector<int>& prices) {
vector<int> minBuy;
vector<int> maxSell;
int maxProfit = 0;
minBuy.push_back(prices[0]);
maxSell.push_back(prices[0]);
for (int i = 1; i < prices.size(); i++) {
if (prices[i] < minBuy[(i - 1)]) {
minBuy.push_back(prices[i]);
maxSell.push_back(prices[i]);
} else {
minBuy.push_back(minBuy[(i - 1)]);
if (prices[i] > maxSell[(i - 1)]) {
maxSell.push_back(prices[i]);
} else {
maxSell.push_back(maxSell[(i - 1)]);
}
}
int profit = maxSell[i] - minBuy[i];
if (profit > maxProfit)
maxProfit = profit;
}
return maxProfit;
}
};