-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy path122.cpp
More file actions
27 lines (27 loc) · 755 Bytes
/
Copy path122.cpp
File metadata and controls
27 lines (27 loc) · 755 Bytes
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
class Solution {
public:
int maxProfit(vector<int> &prices) {
bool bought = false;
auto size = prices.size();
int profit = 0, price = 0;
int i = 0;
while (i < size) {
if (!bought) {
if (prices[i] < prices[i + 1] && i + 1 < size) {
price = prices[i];
bought = true;
}
} else {
if (prices[i] > prices[i + 1] && i + 1 < size) {
profit += (prices[i] - price);
price = 0;
bought = false;
}
}
++i;
}
if (bought)
profit += prices[i - 1] - price;
return profit;
}
};