Untitled

Anonymous
Plain Text
10/17/2025 8:10 PM
1.3 KB
16
Indexable
Never
class Solution {
    public long maxProfit(int[] prices, int[] strategy, int k) {
        long profit = 0;
        long[] profits = new long[prices.length];
        long[] totalSales = new long[prices.length];
        for (int day = 0; day < prices.length; day++) {
            profit += strategy[day] * prices[day];
            profits[day] = profit;
            long prevAccummulativeSale = day == 0 ? 0 : totalSales[day-1];
            totalSales[day] = prevAccummulativeSale + prices[day];
        }

        int left = 0;
        int right = k - 1;
        long maxModifiedProfit = getMaxModifiedProfit(prices, profits, totalSales, left, right, k);

        return Math.max(profit, maxModifiedProfit);
    }

    public long getMaxModifiedProfit(int[] prices, long[] profits, long[] sales, int left, int right, int k) {
        long maxProfit = Long.MIN_VALUE;

        while (right < prices.length) {
            long leftProfit = left > 0 ? profits[left-1] : 0L;

            int offset = k / 2;

            long rightProfit = profits[profits.length-1] - profits[right];
            long rightSubarraySales = sales[right] - sales[right - offset];

            long windowProfit = leftProfit + rightSubarraySales + rightProfit;

            maxProfit = Math.max(maxProfit, windowProfit);

            left++;
            right++;
        }

        return maxProfit;
    }
}
Editor is loading...
Leave a Comment