2897. Apply Operations on Array to Maximize Sum of Squares
</> Solution
/**
* Problem: LeetCode 2897 - Apply Operations on Array to Maximize Sum of Squares
* Difficulty: Hard
* Language: Java
* Author: CodeByTushu
*/
import java.util.List;
/**
* Problem: LeetCode 2897 - Apply Operations on Array to Maximize Sum of Squares
* Difficulty: Hard
* Language: Java
* Author: CodeByTushu
*/
class Solution {
public int maxSum(List<Integer> nums, int k) {
final int MOD = 1_000_000_007;
int[] cnt = new int[30];
for (int num : nums) {
for (int b = 0; b < 30; b++) {
if (((num >> b) & 1) == 1) cnt[b]++;
}
}
long ans = 0;
for (int i = 0; i < k; i++) {
long cur = 0;
for (int b = 0; b < 30; b++) {
if (cnt[b] > 0) {
cur |= (1L << b);
cnt[b]--;
}
}
ans = (ans + (cur % MOD) * (cur % MOD)) % MOD;
}
return (int) ans;
}
}
"""
Problem: LeetCode 2897 - Apply Operations on Array to Maximize Sum of Squares
Difficulty: Hard
Language: Python
Author: CodeByTushu
"""
from typing import List
class Solution:
def maxSum(self, nums: List[int], k: int) -> int:
MOD = 1_000_000_007
cnt = [0] * 30
for num in nums:
for b in range(30):
if (num >> b) & 1:
cnt[b] += 1
ans = 0
for _ in range(k):
cur = 0
for b in range(30):
if cnt[b] > 0:
cur |= (1 << b)
cnt[b] -= 1
ans = (ans + cur * cur) % MOD
return ans
/**
* Problem: LeetCode 2897 - Apply Operations on Array to Maximize Sum of Squares
* Difficulty: Hard
* Language: C++
* Author: CodeByTushu
*/
#include <vector>
using namespace std;
/**
* Problem: LeetCode 2897 - Apply Operations on Array to Maximize Sum of Squares
* Difficulty: Hard
* Language: C++
* Author: CodeByTushu
*/
class Solution {
public:
int maxSum(vector<int>& nums, int k) {
const int MOD = 1'000'000'007;
vector<int> cnt(30, 0);
for (int num : nums) {
for (int b = 0; b < 30; b++) {
if ((num >> b) & 1) {
cnt[b]++;
}
}
}
long long ans = 0;
for (int i = 0; i < k; i++) {
long long cur = 0;
for (int b = 0; b < 30; b++) {
if (cnt[b] > 0) {
cur |= (1LL << b);
cnt[b]--;
}
}
ans = (ans + (cur % MOD) * (cur % MOD)) % MOD;
}
return (int) ans;
}
};
/**
* Problem: LeetCode 2897 - Apply Operations on Array to Maximize Sum of Squares
* Difficulty: Hard
* Language: JavaScript
* Author: CodeByTushu
*/
var maxSum = function(nums, k) {
const MOD = 1000000007n;
const cnt = new Int32Array(30);
for (let i = 0; i < nums.length; i++) {
const num = nums[i];
for (let b = 0; b < 30; b++) {
if ((num >> b) & 1) {
cnt[b]++;
}
}
}
let ans = 0n;
for (let i = 0; i < k; i++) {
let cur = 0n;
for (let b = 0; b < 30; b++) {
if (cnt[b] > 0) {
cur |= (1n << BigInt(b));
cnt[b]--;
}
}
ans = (ans + cur * cur) % MOD;
}
return Number(ans);
};