3573. Best Time to Buy and Sell Stock V #2548
Unanswered
mah-shamim
asked this question in
Q&A
Replies: 1 comment 2 replies
-
|
We need to maximize profit with at most
Key constraints:
Dynamic Programming ApproachWe can use DP with state variables:
State Transitions
Let's implement this solution in PHP: 3573. Best Time to Buy and Sell Stock V <?php
/**
* @param Integer[] $prices
* @param Integer $k
* @return Integer
*/
function maximumProfit($prices, $k) {
$n = count($prices);
// dp[state][t] = max profit with state and t transactions completed
$dp = array_fill(0, 3, array_fill(0, $k + 1, PHP_INT_MIN));
$dp[0][0] = 0;
for ($i = 0; $i < $n; $i++) {
$newDp = $dp;
for ($t = 0; $t <= $k; $t++) {
// From state 0
if ($dp[0][$t] > PHP_INT_MIN) {
// Start long
$newDp[1][$t] = max($newDp[1][$t], $dp[0][$t] - $prices[$i]);
// Start short
$newDp[2][$t] = max($newDp[2][$t], $dp[0][$t] + $prices[$i]);
}
// From state 1
if ($dp[1][$t] > PHP_INT_MIN) {
// Complete long
if ($t < $k) {
$newDp[0][$t + 1] = max($newDp[0][$t + 1], $dp[1][$t] + $prices[$i]);
}
}
// From state 2
if ($dp[2][$t] > PHP_INT_MIN) {
// Complete short
if ($t < $k) {
$newDp[0][$t + 1] = max($newDp[0][$t + 1], $dp[2][$t] - $prices[$i]);
}
}
}
$dp = $newDp;
}
$maxProfit = 0;
for ($t = 0; $t <= $k; $t++) {
$maxProfit = max($maxProfit, $dp[0][$t]);
}
return $maxProfit;
}
// Test cases
echo maximumProfit([[1,7,9,8,2], 2) . "\n"; // Output: 14
echo maximumProfit([12,16,19,19,8,1,19,13,9], 3) . "\n"; // Output: 36
?>Explanation:
Complexity
|
Beta Was this translation helpful? Give feedback.
2 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
-
Topics:
Array,Dynamic Programming,Biweekly Contest 158You are given an integer array
priceswhereprices[i]is the price of a stock in dollars on theiᵗʰday, and an integerk.You are allowed to make at most
ktransactions, where each transaction can be either of the following:i, then sell on a later dayjwherei < j. You profitprices[j] - prices[i].i, then buy back on a later dayjwherei < j. You profitprices[i] - prices[j].Note that you must complete each transaction before starting another. Additionally, you can't buy or sell on the same day you are selling or buying back as part of a previous transaction.
Return the maximum total profit you can earn by making at most
ktransactions.Example 1:
Example 2:
Constraints:
2 <= prices.length <= 10³1 <= prices[i] <= 10⁹1 <= k <= prices.length / 2Hint:
idx,transactionsDone,transactionType,isTransactionRunning.completed -> runningand fromrunning -> completed.Beta Was this translation helpful? Give feedback.
All reactions