[LeetCode] Best Time to Buy and Sell Stock using Strategy

3652. Best Time to Buy and Sell Stock using Strategy

You are given two integer arrays prices and strategy, where:

  • prices[i] is the price of a given stock on the i^th day.
  • strategy[i] represents a trading action on the i^th day, where:
    • -1 indicates buying one unit of the stock.
    • 0 indicates holding the stock.
    • 1 indicates selling one unit of the stock.

You are also given an even integer k, and may perform at most one modification to strategy. A modification consists of:

  • Selecting exactly k consecutive elements in strategy.
  • Set the first k / 2 elements to 0 (hold).
  • Set the last k / 2 elements to 1 (sell).

The profit is defined as the sum of strategy[i] * prices[i] across all days.

Return the maximum possible profit you can achieve.

Note: There are no constraints on budget or stock ownership, so all buy and sell operations are feasible regardless of past actions.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Solution {
public:
long long maxProfit(vector<int>& prices, vector<int>& strategy, int k) {
vector<long long> pre{0}, pos{0};
long long res = LLONG_MIN, n = prices.size();
for(int i = 0; i < n; i++) {
pre.push_back(pre.back() + prices[i] * strategy[i]);
pos.push_back(pos.back() + prices[i]);
}
for(int i = 0; i <= n - k; i++) {
long long now = pre[i] + pre[n] - pre[i+k] + pos[i+k] - pos[i + k / 2];
res = max(res, now);
}
res = max(res, pre.back());
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2026/09/04/PS/LeetCode/best-time-to-buy-and-sell-stock-using-strategy/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.