• + 0 comments

    arr); n + 1, 0);

    // 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