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



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

浙公网安备 33010602011771号