Skip to content

Commit 47d0572

Browse files
authored
Create 3652. Best Time to Buy and Sell Stock using Strategy
1 parent b8a0d0b commit 47d0572

File tree

1 file changed

+47
-0
lines changed

1 file changed

+47
-0
lines changed
Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
class Solution {
2+
public:
3+
long long maxProfit(vector<int>& prices, vector<int>& strategy, int k) {
4+
int n = prices.size();
5+
long long best = 0;
6+
7+
// Compute the profit of the last n-k elements
8+
for (int i = k; i < n; i++) {
9+
best += prices[i] * strategy[i];
10+
}
11+
// Current window: initially will hold profit of n-k elements,
12+
// and add window of first k elements
13+
long long window = best;
14+
15+
for (int i = 0; i < k; i++) {
16+
// Add profit of first k elements to total profit without
17+
// modification
18+
best += prices[i] * strategy[i];
19+
20+
// Add profit for the first window
21+
if (i >= k / 2)
22+
window += prices[i];
23+
}
24+
25+
// Update best for first window
26+
best = max(best, window);
27+
28+
// Adjust window for all remaining elements
29+
for (int i = k; i < n; i++) {
30+
// Change first 0 of previous window to strategy
31+
window += prices[i - k] * strategy[i - k];
32+
33+
// Change the first 1 of previous window to 0
34+
window -= prices[i - k / 2];
35+
36+
// Change strategy to the right of previous window to 1
37+
// Remove strategy value
38+
window -= prices[i] * strategy[i];
39+
// Change to 1
40+
window += prices[i];
41+
42+
// Update best
43+
best = max(best, window);
44+
}
45+
return best;
46+
}
47+
};

0 commit comments

Comments
 (0)