-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathSolution.cpp
43 lines (38 loc) · 1.03 KB
/
Solution.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
37
38
39
40
41
42
43
#include <string>
#include <vector>
#include <iostream>
#include <sstream>
#include <algorithm>
using namespace std;
class Solution {
public:
// greedy ok
int maxProfit(vector<int>& prices) {
if (prices.size() <= 1) return 0;
int maxprofit = 0, minprice = prices[0];
int sum = 0;
for (int i=1; i<prices.size(); i++) {
if (prices[i] < prices[i-1]) {
sum += maxprofit;
minprice = prices[i];
maxprofit = 0;
continue;
}
minprice = prices[i] < minprice ? prices[i] : minprice;
maxprofit = prices[i] - minprice > maxprofit ? prices[i] - minprice : maxprofit;
}
return sum + maxprofit;
}
// extremely short and clean
int maxProfit(vector<int>& prices) {
int sum = 0;
for (int i=1; i<prices.size(); i++) {
int diff = prices[i] > prices[i-1];
sum += diff > 0 ? diff : 0;
}
return sum;
}
};
int main() {
Solution s;
}