3652. Best Time to Buy and Sell Stock using Strategy #2552
-
|
Topics: You are given two integer arrays prices and strategy, where:
You are also given an even integer
The profit is defined as the sum of 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:
Thus, the maximum possible profit is 10, which is achieved by modifying the subarray Example 2:
Thus, the maximum possible profit is 9, which is achieved without any modification. Constraints:
Hint:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
|
We can solve this problem efficiently using prefix sums to compute the profit change for any modification in O(1) time, after O(n) preprocessing. Approach:
Let's implement this solution in PHP: 3652. Best Time to Buy and Sell Stock using Strategy <?php
/**
* @param Integer[] $prices
* @param Integer[] $strategy
* @param Integer $k
* @return Integer
*/
function maxProfit($prices, $strategy, $k) {
$n = count($prices);
$baseProfit = 0;
$prefixPrices = array_fill(0, $n + 1, 0);
$prefixSp = array_fill(0, $n + 1, 0); // prefix of strategy[i] * prices[i]
// Build prefix arrays and compute base profit
for ($i = 0; $i < $n; $i++) {
$baseProfit += $strategy[$i] * $prices[$i];
$prefixPrices[$i + 1] = $prefixPrices[$i] + $prices[$i];
$prefixSp[$i + 1] = $prefixSp[$i] + $strategy[$i] * $prices[$i];
}
$maxDelta = 0;
$half = $k / 2; // k is even
// Try every possible modification window
for ($l = 0; $l <= $n - $k; $l++) {
$sumPricesSecondHalf = $prefixPrices[$l + $k] - $prefixPrices[$l + $half];
$sumOldSegment = $prefixSp[$l + $k] - $prefixSp[$l];
$delta = $sumPricesSecondHalf - $sumOldSegment;
if ($delta > $maxDelta) {
$maxDelta = $delta;
}
}
return $baseProfit + $maxDelta;
}
// Test cases
echo maxProfit([4,2,8], [-1,0,1], 2) . "\n"; // Output: 10
echo maxProfit([5,4,3], [1,1,0], 2) . "\n"; // Output: 9
?>Explanation:
Complexity Analysis
|
Beta Was this translation helpful? Give feedback.
We can solve this problem efficiently using prefix sums to compute the profit change for any modification in O(1) time, after O(n) preprocessing.
Approach:
Let's implement this solution in PHP: 36…