LeetCode 2897: Apply Operations on Array to Maximize Sum of Squares
Problem Description
Explanation:
This problem can be solved using a greedy approach. We need to maximize the sum of squares by choosing k elements from the array after performing a specified operation on the elements. The key idea is to realize that performing the given operation on any two elements results in one element being set to 0 and the other having all its bits set. Hence, the optimal strategy is to select k largest elements from the array after performing the operation. Solution:
Solutions
class Solution {
public int maxSumOfSquares(int[] nums, int k) {
Arrays.sort(nums);
int n = nums.length;
long mod = 1000000007;
long sum = 0;
for (int i = n - 1; i >= n - k; i--) {
sum = (sum + (long)nums[i] * nums[i]) % mod;
}
return (int)sum;
}
}
Loading editor...