Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Leetcode 2681. Power of Heroes #256

Open
Woodyiiiiiii opened this issue May 17, 2023 · 0 comments
Open

Leetcode 2681. Power of Heroes #256

Woodyiiiiiii opened this issue May 17, 2023 · 0 comments

Comments

@Woodyiiiiiii
Copy link
Owner

Leetcode 2681. Power of Heroes

2681. Power of Heroes
贡献法(Python/Java/C++/Go)

看到题目关键条件max * max * min,加上要求所有序列,所以想到与排序无关,直接排序。

然后做的就是分析示例,摸清想法了。假设排好序的数组[a,b,c,d],我们可以得到以下计算公式:a * a * a,b * b * b + b * b * a,c * c * c + c * c * b + c * c * a * 2,d * d * d + d * d * c + d * d * b * 2 + d * d * a * 4. 可以发现有规律,计算式子之间有递进关系。

接着,是一个关键的思路选择问题。假设我们从左往右遍历,以当前nums[i]值作为min值,会发现是个递减关系,要用逆元来做,太麻烦了,所以不妨把nums[i]值设置为max值。

抛开当前值,可以发现每个值与前面的值比较是乘2再加上nums[i-1]。

最后注意要MOD,乘法的MOD最后%就好。

class Solution {
    public int sumOfPower(int[] nums) {
        final int MOD = (int)1e9 + 7;
        Arrays.sort(nums);
        long ans = 0, k = 0;
        for (int i = 0; i < nums.length; i++) {
            long numL = nums[i];
            long num = numL * numL % MOD;
            long pre = (k + nums[i]) % MOD;
            ans = (ans + num * pre % MOD) % MOD;
            k = (k * 2 % MOD + nums[i]) % MOD;
        }
        return (int)ans;
    }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant