2026年10月12日 星期一

LeetCode 解題筆記:2897. Apply Operations on Array to Maximize Sum of Squares

作者:王一哲
日期:2026年10月12日


LeetCode 題目連結:2897. Apply Operations on Array to Maximize Sum of Squares

解題想法


困難題。題目給一個整數陣列 $nums$,每次操作可以取任意兩個不同的索引值 $i, j$,同時將 $nums[i]$ 改成 nums[i] & nums[j],$nums[j]$ 改成 nums[i] | nums[j],操作次數不限。從 $nums$ 之中取 $k$ 個數字,求這 $k$ 個數字平方和最大值。

這題底下的提示1提到,這個操作過程只是移動 1,例如 1000 = 11111010002, 500 = 1111101002,共有 $12$ 個 $1$,操作後 1000 & 500 = 1111000002,1000 | 500 = 11111111002 還是 $12$ 個 $1$。提示2有說可以用貪心法找最大平方和,這是基於提示1,由於 $1$ 的總數固定,盡量將 $1$ 集中到前 $k$ 個大的數字,可以使平方和最大化。由這兩個提示開始寫程式碼即可。

Python 程式碼


Runtime: 1409 ms, beats 44.68%. Memory: 31.96 MB, beats 76.60%.
class Solution:
    def maxSum(self, nums, k) -> int:
        # 1. 統計每個位數有幾個 1,因為 nums[i] <= 10**9 < 2**31,長度開 32 就夠用
        cnt = [0] * 32  # 0 ~ 31 位各有幾個 1
        for num in nums:
            for i in range(32):
                if (num >> i) & 1:
                    cnt[i] += 1

        # 2. 用貪心法重組出 k 個最大的數字,過程中同時取餘數
        ans = 0
        mod = 10**9 + 7
        for _ in range(k):
            val = 0
            for i in range(32):
                if cnt[i] > 0:
                    val |= (1 << i)
                    cnt[i] -= 1
            ans = (ans + val * val % mod) % mod

        return ans


C++ 程式碼


Runtime: 39 ms, beats 93.55%. Memory: 90.42 MB, beats 87.10%.
class Solution {
public:
    int maxSum(vector<int>& nums, int k) {
        /* 1. 統計每個位數有幾個 1,因為 nums[i] <= 10**9 < 2**31,長度開 32 就夠用 */
        int cnt[32] = {0};
        for(int num : nums) {
            for(int i = 0; i < 32; i++) {
                if ((num >> i) & 1) {
                    cnt[i]++;
                }
            }
        }

        /* 2. 用貪心法重組出 k 個最大的數字,過程中同時取餘數 */
        long ans = 0;
        const int mod = 1000000007;
        for(int i = 0; i < k; i++) {
            long val = 0;  // 計算答案時需要求 val * val,可能會超出 int 的範圍
            for(int j = 0; j < 32; j++) {
                if (cnt[j] > 0) {
                    val |= (1 << j);
                    cnt[j]--;
                }
            }
            ans = (ans + val * val % mod) % mod;
        }
        return (int)ans;
    }
};


C 語言程式碼


Runtime: 83 ms, beats 100.00%. Memory: 18.10 MB, beats 100.00%.
int maxSum(int* nums, int numsSize, int k) {
    /* 1. 統計每個位數有幾個 1,因為 nums[i] <= 10**9 < 2**31,長度開 32 就夠用 */
    int cnt[32] = {0};
    for(int i = 0; i < numsSize; i++) {
        for(int j = 0; j < 32; j++) {
            if ((nums[i] >> j) & 1) {
                cnt[j]++;
            }
        }
    }

    /* 2. 用貪心法重組出 k 個最大的數字,過程中同時取餘數 */
    long ans = 0;
    const int mod = 1000000007;
    for(int i = 0; i < k; i++) {
        long val = 0;  // 計算答案時需要求 val * val,可能會超出 int 的範圍
        for(int j = 0; j < 32; j++) {
            if (cnt[j] > 0) {
                val |= (1 << j);
                cnt[j]--;
            }
        }
        ans = (ans + val * val % mod) % mod;
    }
    return (int)ans;
}


沒有留言:

張貼留言