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.
1using System;
2
3public class Solution {
4 public int MaximumScore(int[] nums, int[] multipliers) {
5 int n = nums.Length, m = multipliers.Length;
6 int[,] dp = new int[m + 1, m + 1];
7 for (int i = m - 1; i >= 0; i--) {
8 for (int left = i; left >= 0; left--) {
9 dp[i, left] = Math.Max(
10 multipliers[i] * nums[left] + dp[i + 1, left + 1],
11 multipliers[i] * nums[n - 1 - (i - left)] + dp[i + 1, left]
12 );
13 }
14 }
15 return dp[0, 0];
16 }
17}
The C# solution also uses a 2D DP table to predict the maximum scores based on possible decisions to be made at each stage of the algorithm. The scores are calculated and stored in the table, and the maximum score returned is stored in dp[0, 0]
.
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.
1#include <stdio.h>
2
3int maximumScore(int* nums, int numsSize, int* multipliers, int multipliersSize) {
4 int left = 0, right = numsSize - 1;
5 int score = 0;
6 for (int i = 0; i < multipliersSize; ++i) {
7 if (multipliers[i] * nums[left] >= multipliers[i] * nums[right]) {
8 score += multipliers[i] * nums[left++];
9 } else {
10 score += multipliers[i] * nums[right--];
11 }
12 }
13 return score;
14}
This C implementation follows the same greedy strategy, adjusting the current score at each iteration by selecting the more beneficial option between the two endpoints of the nums
array, dictated by comparing their products with the current multiplier.