Skip to content

Commit 3ea592b

Browse files
💰 Day 18
1 parent 71ccd34 commit 3ea592b

File tree

2 files changed

+33
-0
lines changed

2 files changed

+33
-0
lines changed

README.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,8 @@
2929
1. [Rotate Array](https://leetcode.com/explore/challenge/card/october-leetcoding-challenge/561/week-3-october-15th-october-21st/3496/) ➡️ [CPP Solution](Week3/rotate.cpp)
3030
2. [Search a 2D Matrix](https://leetcode.com/explore/challenge/card/october-leetcoding-challenge/561/week-3-october-15th-october-21st/3497/) ➡️ [CPP Solution](Week3/searchMatrix.cpp)
3131
3. [Repeated DNA Sequences](https://leetcode.com/explore/challenge/card/october-leetcoding-challenge/561/week-3-october-15th-october-21st/3498/) ➡️ [CPP Solution](Week3/findRepeatedDnaSequences.cpp)
32+
4. [Best Time to Buy and Sell Stock IV](https://leetcode.com/explore/challenge/card/october-leetcoding-challenge/561/week-3-october-15th-october-21st/3499/) ➡️ [CPP Solution](Week3/maxProfit.cpp)
33+
3234

3335
## Week 4 🚧
3436

Week3/maxProfit.cpp

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
class Solution {
2+
public:
3+
int maxProfit(int k, vector<int>& prices) {
4+
int n = prices.size();
5+
6+
if(n <= 1 || k <= 0) return 0;
7+
8+
int profit = 0;
9+
if(k >= n / 2) {
10+
for(int i = 0; i < n - 1; ++i) {
11+
if(prices[i + 1] > prices[i])
12+
profit += prices[i + 1] - prices[i];
13+
}
14+
15+
return profit;
16+
}
17+
18+
int buy[k], sell[k];
19+
fill(buy, buy + k, INT_MIN);
20+
fill(sell, sell + k, 0);
21+
22+
for(int i = 0; i < n; ++i) {
23+
for(int j = 0; j < k; ++j) {
24+
buy[j] = max(buy[j], j == 0 ? 0 - prices[i] : sell[j - 1] - prices[i]);
25+
sell[j] = max(sell[j], buy[j] + prices[i]);
26+
}
27+
}
28+
29+
return sell[k - 1];
30+
}
31+
};

0 commit comments

Comments
 (0)