This approach involves using dynamic programming to keep track of the maximum scores obtainable by choosing elements from either the start or the end of the nums array during each step of the operations defined by the multipliers array. We maintain a 2D DP table where dp[i][j] represents the maximum score obtained by using the first (i + j) elements from nums, where i elements have been chosen from the start, and j elements have been chosen from the end.
Time Complexity: O(m^2), where m is the length of the multipliers array, because we're filling an m x m DP table.
Space Complexity: O(m^2) due to the storage requirements of the m x m DP table.
1function maximumScore(nums, multipliers) {
2 let n = nums.length, m = multipliers.length;
3 let dp = Array.from({length: m + 1}, () => Array(m + 1).fill(0));
4 for (let i = m - 1; i >= 0; --i) {
5 for (let left = i; left >= 0; --left) {
6 dp[i][left] = Math.max(
7 multipliers[i] * nums[left] + dp[i + 1][left + 1],
8 multipliers[i] * nums[n - 1 - (i - left)] + dp[i + 1][left]
9 );
10 }
11 }
12 return dp[0][0];
13}
This JavaScript version constructs a two-dimensional array to track potential scores achieved at each decision point. It saves optimal outcomes in the DP matrix for each operation and returns the maximum possible score found.
This approach uses a simpler greedy strategy to try and choose the best possible option at each step, based on examining both the start and end of the nums array for potential scores. It evaluates which element, when multiplied with the current multiplier, gives the maximum increase in the score and selects that iteratively through all operations.
Time Complexity: O(m), where m is the number of operations.
Space Complexity: O(1), utilizing constant space regardless of input size.
1class Solution {
2 public int maximumScore(int[] nums, int[] multipliers) {
3 int left = 0, right = nums.length - 1;
4 int score = 0;
5 for (int multiplier : multipliers) {
6 if (multiplier * nums[left] >= multiplier * nums[right]) {
7 score += multiplier * nums[left++];
8 } else {
9 score += multiplier * nums[right--];
10 }
11 }
12 return score;
13 }
14}
A greedy approach gradually checks the prospective results of the current multiplier when multiplied with the outer values of the nums
array, continuously advancing the endpoints based on which is larger for optimizing the score.