We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
// Base cases
$dp[0] = 0; // If no bricks, score is 0
`$dp[1] = $`arr[0]; // If only one brick, score is the value of that brick
// Loop to calculate maximum score
for (`$i = 2; $`i <= `$n; $`i++) {
// At each step, we have three options: take 1, 2, or 3 bricks
// We choose the option that minimizes the opponent's score
`$dp[$`i] = max(
`$arr[$`i - 1] + `$arr[$`i - 2] + (`$i >= 4 ? $`dp[$i - 3] : 0), // Take 3 bricks
`$arr[$`i - 1] + (`$i >= 3 ? $`arr[`$i - 2] + $`dp[$i - 2] : 0), // Take 2 bricks
`$arr[$`i - 1] + `$dp[$`i - 1] // Take 1 brick
);
}
return `$dp[$`n]; // Return the maximum score
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Bricks Game
You are viewing a single comment's thread. Return to all comments →
arr); n + 1, 0);