
Sponsored
Sponsored
This approach uses backtracking to explore all possible pairs of elements for the operations. The goal is to maximize the sum of scores obtained from each operation. To optimize the solution, pruning is applied by avoiding redundant calculations using a memoization table. By systematically trying all combinations, we gradually eliminate suboptimal solutions and select the maximal score possible.
Time Complexity: O((2n)! / 2^n), the approach explores all possible combinations of pairs.
Space Complexity: O(2^n), for memoization array to store intermediate results.
1from math import gcd
2from functools import lru_cache
3
4class Solution:
5 def maxScore(self, nums):
6 n = len(nums)
7
8 @lru_cache(None)
9 def backtrack(used):
10 if used == (1 << n) - 1:
11 return 0
12 max_score = 0
13 for i in range(n):
14 if not used & (1 << i):
15 for j in range(i + 1, n):
16 if not used & (1 << j):
17 score = gcd(nums[i], nums[j]) * (bin(used).count('1') // 2 + 1)
18 max_score = max(max_score, score + backtrack(used | (1 << i) | (1 << j)))
19 return max_score
20
21 return backtrack(0)
22
23print(Solution().maxScore([1, 2, 3, 4, 5, 6]))This Python solution uses recursion with LRU caching to store intermediate results and avoid recalculations. The use of bit manipulation effectively tracks used elements and allowed potential score maximization through backtracking.
This approach leverages dynamic programming along with bit masking to compute the maximum score possible. The idea is to use a DP state to remember the best score possible with a certain combination of pairs already taken. The state is determined by a bitmask which indicates the taken pairs. Recursively calculate the maximum possible score, storing intermediate results to avoid repeated calculations.
Time Complexity: O(n^2 * 2^n), where n is the number of elements in 'nums'.
Space Complexity: O(2^n) for the DP array.
public class MaxScore {
public static int GCD(int a, int b) {
while (b != 0) {
int temp = b;
b = a % b;
a = temp;
}
return a;
}
public static int MaxScore(int[] nums) {
int n = nums.Length / 2;
int[] dp = new int[1 << nums.Length];
Array.Fill(dp, int.MinValue);
dp[0] = 0;
for (int mask = 0; mask < (1 << nums.Length); ++mask) {
int ops = BitCount(mask) / 2 + 1;
for (int i = 0; i < nums.Length; ++i) {
if ((mask & (1 << i)) == 0) {
for (int j = i + 1; j < nums.Length; ++j) {
if ((mask & (1 << j)) == 0) {
int new_mask = mask | (1 << i) | (1 << j);
dp[new_mask] = Math.Max(dp[new_mask], dp[mask] + ops * GCD(nums[i], nums[j]));
}
}
}
}
}
return dp[(1 << nums.Length) - 1];
}
public static int BitCount(int n) {
int count = 0;
while (n != 0) {
count += n & 1;
n >>= 1;
}
return count;
}
public static void Main() {
int[] nums = {1, 2, 3, 4, 5, 6};
Console.WriteLine("Max Score: " + MaxScore(nums));
}
}C# employs DP using bitmasking to store and update scores for different sets of paired selections, aiming to capture the maximal achievable score.