LeetCode-in-Java

3652. Best Time to Buy and Sell Stock using Strategy

Medium

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

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

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:

Solution

public class Solution {
    public long maxProfit(int[] p, int[] s, int k) {
        int n = p.length;
        long[] p1 = new long[n + 1];
        long[] p2 = new long[n + 1];
        for (int i = 0; i < n; i++) {
            p1[i + 1] = p1[i] + (long) s[i] * p[i];
            p2[i + 1] = p2[i] + p[i];
        }
        long max = 0;
        for (int i = 0; i <= n - k; i++) {
            int m = i + k / 2;
            int e = i + k;
            long op = p1[e] - p1[i];
            long np = p2[e] - p2[m];
            max = Math.max(max, np - op);
        }
        return p1[n] + max;
    }
}