20251219按策略买卖股票的最佳时机

image
image
image

class Solution {
    public long maxProfit(int[] prices, int[] strategy, int k) {
        int n = prices.length;
        long[] profitSum =  new long[n + 1];
        long[] pricesSum = new long[n + 1];
        profitSum[0] = (long)prices[0] * strategy[0];
        pricesSum[0] = prices[0];
        for (int i = 1; i < n; ++i) {
            profitSum[i] = profitSum[i - 1] + (long)prices[i] * strategy[i];
            pricesSum[i] = pricesSum[i - 1] + prices[i];
        }
        long res = profitSum[n - 1];
        for (int i = k - 1; i < n; ++i) {
            long leftProfit = i - k < 0 ? 0 : profitSum[i - k];
            long rightProfit = profitSum[n - 1] - profitSum[i];
            long changeProfit = pricesSum[i] - (i - k / 2 < 0 ? 0 : pricesSum[i - k / 2]);
            res = Math.max(res, leftProfit + changeProfit + rightProfit);
        }
        return res;
    }
}
~~~java
posted @ 2025-12-19 14:41  一步两世  阅读(0)  评论(0)    收藏  举报