Skip to content

Commit d0a80b0

Browse files
committed
add maxProfit.cpp
1 parent c80e033 commit d0a80b0

File tree

3 files changed

+71
-0
lines changed

3 files changed

+71
-0
lines changed

C++/maxProfitI.cpp

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
// Time Complexity: O(n)
2+
// Space Complexity: O(1)
3+
4+
class Solution {
5+
public:
6+
int maxProfit(vector<int> &prices) {
7+
const int n = prices.size();
8+
9+
if(n < 2)
10+
return 0;
11+
12+
// Greedy Algorithm
13+
int ans = 0;
14+
for(int i = 1, valley = prices[0]; i < n; ++i) {
15+
ans = max(ans, prices[i] - valley);
16+
valley = min(valley, prices[i]);
17+
}
18+
19+
return ans;
20+
}
21+
};

C++/maxProfitII.cpp

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
// Time Complexity: O(n)
2+
// Space Complexity: O(1)
3+
4+
class Solution {
5+
public:
6+
int maxProfit(vector<int> &prices) {
7+
const int n = prices.size();
8+
int ans = 0;
9+
10+
for(int i = 1; i < n; ++i) {
11+
int diff = prices[i] - prices[i - 1];
12+
if(diff > 0)
13+
ans += diff;
14+
}
15+
16+
return ans;
17+
}
18+
};

C++/maxProfitIII.cpp

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
// Time Complexity: O(n)
2+
// Space Complexity: O(n)
3+
4+
class Solution {
5+
public:
6+
int maxProfit(vector<int> &prices) {
7+
const int n = prices.size();
8+
9+
if(n < 2)
10+
return 0;
11+
12+
vector<int> f(n, 0);
13+
vector<int> g(n, 0);
14+
15+
for(int i = 1, valley = prices[0]; i < n; ++i) {
16+
f[i] = max(f[i - 1], prices[i] - valley);
17+
valley = min(valley, prices[i]);
18+
}
19+
20+
for(int i = n - 2, peak = prices[n - 1]; i >= 0; --i) {
21+
g[i] = max(g[i + 1], peak - prices[i]);
22+
peak = max(peak, prices[i]);
23+
}
24+
25+
int ans = 0;
26+
for(int i = 0; i < n; ++i) {
27+
ans = max(ans, f[i] + g[i]);
28+
}
29+
30+
return ans;
31+
}
32+
};

0 commit comments

Comments
 (0)