1770. Maximum Score from Performing Multiplication Operations

Explanation

To solve this problem, we can use dynamic programming with memoization. We can define a function that takes two pointers left and index to represent the current state of the arrays. At each step, we have two choices: either pick the element at the left pointer from the start of nums or pick the element at the left pointer from the end of nums. We can calculate the score for both choices recursively and keep track of the maximum score obtained.

We use a 2D memoization array to store the scores previously calculated to avoid redundant calculations. The state can be represented by two pointers left and index, where left ranges from 0 to m and index ranges from 0 to n. The base case is when left reaches m, we return 0, and otherwise, we calculate the score recursively based on the two choices mentioned above.

The time complexity of this approach is O(m^2) because there are m * n states to compute, and each state involves constant time operations. The space complexity is also O(m^2) due to the memoization array.

class Solution {
    public int maximumScore(int[] nums, int[] multipliers) {
        int m = multipliers.length;
        int n = nums.length;
        int[][] memo = new int[m + 1][m + 1];
        return dfs(nums, multipliers, 0, 0, m, memo);
    }
    
    private int dfs(int[] nums, int[] multipliers, int left, int index, int m, int[][] memo) {
        if (index == m) {
            return 0;
        }
        
        if (memo[left][index] != 0) {
            return memo[left][index];
        }
        
        int pickStart = multipliers[index] * nums[left] + dfs(nums, multipliers, left + 1, index + 1, m, memo);
        int pickEnd = multipliers[index] * nums[nums.length - (index - left) - 1] + dfs(nums, multipliers, left, index + 1, m, memo);
        
        memo[left][index] = Math.max(pickStart, pickEnd);
        return memo[left][index];
    }
}

Code Editor (Testing phase)

Improve Your Solution

Use the editor below to refine the provided solution. Select a programming language and try the following:

  • Add import statement if required.
  • Optimize the code for better time or space complexity.
  • Add test cases to validate edge cases and common scenarios.
  • Handle error conditions or invalid inputs gracefully.
  • Experiment with alternative approaches to deepen your understanding.

Click "Run Code" to execute your solution and view the output. If errors occur, check the line numbers and debug accordingly. Resize the editor by dragging its bottom edge.