LeetCode 1770. Maximum Score from Performing Multiplication Operations

原题链接在这里:https://leetcode.com/problems/maximum-score-from-performing-multiplication-operations/

题目:

You are given two integer arrays nums and multipliers of size n and m respectively, where n >= m. The arrays are 1-indexed.

You begin with a score of 0. You want to perform exactly m operations. On the ith operation (1-indexed), you will:

  • Choose one integer x from either the start or the end of the array nums.
  • Add multipliers[i] * x to your score.
  • Remove x from the array nums.

Return the maximum score after performing m operations.

Example 1:

Input: nums = [1,2,3], multipliers = [3,2,1]
Output: 14
Explanation: An optimal solution is as follows:
- Choose from the end, [1,2,3], adding 3 * 3 = 9 to the score.
- Choose from the end, [1,2], adding 2 * 2 = 4 to the score.
- Choose from the end, [1], adding 1 * 1 = 1 to the score.
The total score is 9 + 4 + 1 = 14.

Example 2:

Input: nums = [-5,-3,-3,-2,7,1], multipliers = [-10,-5,3,4,6]
Output: 102
Explanation: An optimal solution is as follows:
- Choose from the start, [-5,-3,-3,-2,7,1], adding -5 * -10 = 50 to the score.
- Choose from the start, [-3,-3,-2,7,1], adding -3 * -5 = 15 to the score.
- Choose from the start, [-3,-2,7,1], adding -3 * 3 = -9 to the score.
- Choose from the end, [-2,7,1], adding 1 * 4 = 4 to the score.
- Choose from the end, [-2,7], adding 7 * 6 = 42 to the score. 
The total score is 50 + 15 - 9 + 4 + 42 = 102.

Constraints:

  • n == nums.length
  • m == multipliers.length
  • 1 <= m <= 103
  • m <= n <= 105
  • -1000 <= nums[i], multipliers[i] <= 1000

题解:

dp(l, r, i) could be calculated as maximum of dp(l + 1, r, i + 1) + nums[l] * muls[i], dp(l , r + 1, i + 1) * nums[r] * muls[i].

Here r could be calculated by l and i.

r = n - (rightTaken) - 1 

rightTaken = i - leftTaken = i - l.

r = n - (i - l) - 1 = n - i + l - 1.

Time Complexity: O(m ^ 2).

Space: O(m ^ 2).

AC Java:

 1 class Solution {
 2     int n;
 3     int m;
 4     Integer [][] memo;
 5     int [] nums;
 6     int [] muls;
 7     public int maximumScore(int[] nums, int[] multipliers) {
 8         n = nums.length;
 9         m = multipliers.length;
10         this.memo = new Integer[m][m];
11         this.nums = nums;
12         this.muls = multipliers;
13         
14         return dfs(0, 0);
15     }
16     
17     private int dfs(int l, int i){
18         if(i == m){
19             return 0;
20         }
21         
22         if(memo[l][i] != null){
23             return memo[l][i];
24         }
25         
26         int left = dfs(l + 1, i + 1) + nums[l] * muls[i];
27         int right = dfs(l, i + 1) + nums[n - i + l - 1] * muls[i];
28         return memo[l][i] = Math.max(left, right);
29     }
30 }

 

posted @ 2022-09-16 11:01  Dylan_Java_NYC  阅读(67)  评论(0)    收藏  举报