LeetCode 3282: Reach End of Array With Max Score

ArrayGreedy

Problem Description

Explanation:

To solve this problem, we can use dynamic programming to keep track of the maximum score that can be achieved at each index. At each index i, we calculate the score for jumping from the previous indices to index i, and update the maximum score at index i.

  1. Create an array dp of size n to store the maximum score at each index.
  2. Initialize dp[0] to 0 as the maximum score at the starting index.
  3. Iterate over the array from index 1 to n-1.
  4. For each index i, calculate the score for jumping from previous indices to index i and update dp[i] with the maximum score.
  5. Finally, return dp[n-1] which represents the maximum possible total score by reaching the last index.

Solutions

class Solution {
    public int maxScore(int[] nums) {
        int n = nums.length;
        int[] dp = new int[n];
        dp[0] = 0;
        
        for (int i = 1; i < n; i++) {
            dp[i] = Integer.MIN_VALUE;
            for (int j = 0; j < i; j++) {
                dp[i] = Math.max(dp[i], dp[j] + (i - j) * nums[j]);
            }
        }
        
        return dp[n - 1];
    }
}

Loading editor...