Skip to content

Instantly share code, notes, and snippets.

@tatsuyax25
Created December 18, 2025 18:10
Show Gist options
  • Select an option

  • Save tatsuyax25/1bf5330b5330fb534db825c8f0db4ea8 to your computer and use it in GitHub Desktop.

Select an option

Save tatsuyax25/1bf5330b5330fb534db825c8f0db4ea8 to your computer and use it in GitHub Desktop.
You are given two integer arrays prices and strategy, where: prices[i] is the price of a given stock on the ith day. strategy[i] represents a trading action on the ith day, where: -1 indicates buying one unit of the stock. 0 indicates holding the st
/**
* Calculates the maximum profit achievable by applying a strategy
* and replacing a window of size `k` with a new profit calculation.
*
* @param {number[]} prices - Array of prices over time.
* @param {number[]} strategy - Strategy multipliers applied to each price.
* @param {number} k - Size of the window to adjust.
* @returns {number} Maximum profit achievable.
*/
var maxProfit = function(prices, strategy, k) {
const n = prices.length;
let maxProfit = 0;
// Prefix sums for cumulative values and profits
const prefixSumPrices = new Array(n);
const prefixSumProfit = new Array(n);
// Initialize prefix sums with the first element
prefixSumPrices[0] = prices[0];
prefixSumProfit[0] = prices[0] * strategy[0];
// Build prefix sums for prices and profits
for (let i = 1; i < n; i++) {
prefixSumPrices[i] = prices[i] + prefixSumPrices[i - 1];
prefixSumProfit[i] = prefixSumProfit[i - 1] + prices[i] * strategy[i];
}
// Current profit using the full strategy
const baseProfit = prefixSumProfit[n - 1];
maxProfit = baseProfit;
// Try replacing each window of size k
for (let left = 0; left <= n - k; left++) {
const right = left + k - 1;
// Profit contributed by the current window [left, right]
let windowProfit = prefixSumProfit[right];
if (left > 0) {
windowProfit -= prefixSumProfit[left - 1];
}
// New profit if we replace the second half of the window
const mid = left + Math.floor(k / 2) - 1;
const newWindowProfit = prefixSumPrices[right] - prefixSumPrices[mid];
// Adjusted profit: remove old window profit, add new window profit
const adjustedProfit = baseProfit - windowProfit + newWindowProfit;
// Track maximum profit
maxProfit = Math.max(maxProfit, adjustedProfit);
}
return maxProfit;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment