Best Time to Buy and Sell Stock using Strategy Problem
Description
LeetCode Problem 3652.
You are given two integer arrays prices and strategy, where:
prices[i]is the price of a given stock on thei^thday.strategy[i]represents a trading action on thei^thday, where:-1indicates buying one unit of the stock.0indicates holding the stock.1indicates 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
kconsecutive elements instrategy. - Set the first
k / 2elements to0(hold). - Set the last
k / 2elements to1(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.
Example 1:
Input: prices = [4,2,8], strategy = [-1,0,1], k = 2
Output: 10
Explanation:
Modification Strategy Profit Calculation Profit
Original [-1, 0, 1] (-1 × 4) + (0 × 2) + (1 × 8) = -4 + 0 + 8 4
Modify [0, 1] [0, 1, 1] (0 × 4) + (1 × 2) + (1 × 8) = 0 + 2 + 8 10
Modify [1, 2] [-1, 0, 1] (-1 × 4) + (0 × 2) + (1 × 8) = -4 + 0 + 8 4
Thus, the maximum possible profit is 10, which is achieved by modifying the subarray [0, 1].
Example 2:
Input: prices = [5,4,3], strategy = [1,1,0], k = 2
Output: 9
Explanation:
Modification Strategy Profit Calculation Profit
Original [1, 1, 0] (1 × 5) + (1 × 4) + (0 × 3) = 5 + 4 + 0 9
Modify [0, 1] [0, 1, 0] (0 × 5) + (1 × 4) + (0 × 3) = 0 + 4 + 0 4
Modify [1, 2] [1, 0, 1] (1 × 5) + (0 × 4) + (1 × 3) = 5 + 0 + 3 8
Thus, the maximum possible profit is 9, which is achieved without any modification.
Constraints:
2 <= prices.length == strategy.length <= 10^51 <= prices[i] <= 10^5-1 <= strategy[i] <= 12 <= k <= prices.lengthkis even
Solution
Approach: Prefix Sums and Enumeration
Let s[i] be the profit of the first i days under the original strategy (sum of prices[j] * strategy[j]) and t[i] the sum of the first i prices.
If we change the window of k days ending at day i, the first half of it becomes 0 (hold) and the second half becomes 1 (sell). The profit from those days changes from s[i] - s[i - k] to the sum of the last k / 2 prices, t[i] - t[i - k/2]. So the total profit is
s[n] - (s[i] - s[i - k]) + (t[i] - t[i - k/2]).
Try every end i from k to n, take the best of these values, and also compare with the unchanged profit s[n] (we may skip the modification).
Complexity: O(n) time and O(n) extra space.
class Solution:
def maxProfit(self, prices: List[int], strategy: List[int], k: int) -> int:
n = len(prices)
s = [0] * (n + 1)
t = [0] * (n + 1)
for i, (a, b) in enumerate(zip(prices, strategy), 1):
s[i] = s[i - 1] + a * b
t[i] = t[i - 1] + a
ans = s[n]
for i in range(k, n + 1):
ans = max(ans, s[n] - (s[i] - s[i - k]) + t[i] - t[i - k // 2])
return ans