1799. Maximize Score After N Operations
Solutions
class Solution {
public:
int maxScore(vector<int>& nums) {
int n = nums.size();
vector<vector<int>> g(n, vector<int>(n));
for (int i = 0; i < n; i++)
for (int j = i + 1; j < n; j++)
g[i][j] = gcd(nums[i], nums[j]);
int final_state = 1 << n;
vector<int> dp(final_state);
for (int s = 0; s < final_state; s++) {
int count = __builtin_popcount(s);
if (count & 1) continue;
for (int i = 0; i < n; i++)
for (int j = i + 1; j < n; j++) {
if ((s & (1 << i)) || (s & (1 << j)))
continue;
int ns = s | (1 << i) | (1 << j);
dp[ns] = max(dp[ns], dp[s] + g[i][j] * ((count / 2) + 1));
}
}
return dp.back();
}
};Last updated