-
Notifications
You must be signed in to change notification settings - Fork 0
/
0121.cpp
44 lines (42 loc) · 1.04 KB
/
0121.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
44
class Solution {
public:
int maxProfit(vector<int> &prices) {
// return func1(prices);
// return func2(prices);
return func3(prices);
}
// ** O(n^2)
int func1(vector<int> &prices) {
int max = 0;
for (int i = 0; i < prices.size(); i++) {
for (int j = i + 1; j < prices.size(); j++) {
if (prices[j] - prices[i] > max) {
max = prices[j] - prices[i];
}
}
}
return max;
}
// ** O(n)
int func2(vector<int> &prices) {
if (prices.size() <= 0) {
return 0;
}
int maxProfit = 0;
int minPrice = prices[0];
for (int i = 0; i < prices.size(); i++) {
minPrice = min(minPrice, prices[i]);
maxProfit = max(maxProfit, prices[i] - minPrice);
}
return maxProfit;
}
int func3(vector<int> &prices) {
int maxProfit = 0;
int minIndex = 0;
for (int i = 0; i < prices.size(); i++) {
minIndex = prices[i] < prices[minIndex] ? i : minIndex;
maxProfit = max(maxProfit, prices[i] - prices[minIndex]);
}
return maxProfit;
}
};