Input: nums =[1,2,3,4], k =3Output: 4Explanation:
There are 4 subsequences in`nums` which have length 3:`[1,2,3]`,`[1,3,4]`,`[1,2,4]`, and `[2,3,4]`. The sum of powers is`|2 - 3| + |3 - 4| + |2 - 1| +
|3 - 4| = 4`.
Input: nums =[4,3,-1], k =2Output: 10Explanation:
There are 3 subsequences in`nums` which have length 2:`[4,3]`,`[4,-1]`, and
`[3,-1]`. The sum of powers is`|4 - 3| + |4 - (-1)| + |3 - (-1)| = 10`.
For each subsequence of length k, its power is the minimum absolute difference between any two elements. If we sort the array, the minimum difference in a k-length subsequence is always between two adjacent elements. We can use dynamic programming to count the number of ways to pick k elements and keep track of the minimum difference.
classSolution {
publicintsumOfPowers(int[] nums, int k) {
int MOD = 1_000_000_7;
int n = nums.length;
Arrays.sort(nums);
long[][] dp =newlong[n + 1][k + 1];
for (int i = 0; i < n; ++i) dp[i][1]= 1;
for (int j = 2; j <= k; ++j) {
for (int i = j - 1; i < n; ++i) {
for (int p = j - 2; p < i; ++p) {
int diff = nums[i]- nums[p];
dp[i][j]= (dp[i][j]+ dp[p][j - 1]* diff) % MOD;
}
}
}
long ans = 0;
for (int i = k - 1; i < n; ++i) ans = (ans + dp[i][k]) % MOD;
return (int)ans;
}
}
classSolution {
funsumOfPowers(nums: IntArray, k: Int): Int {
val MOD = 1_000_000_7
val n = nums.size
nums.sort()
val dp = Array(n + 1) { LongArray(k + 1) }
for (i in0 until n) dp[i][1] = 1Lfor (j in2..k) {
for (i in j - 1 until n) {
for (p in j - 2 until i) {
val diff = nums[i] - nums[p]
dp[i][j] = (dp[i][j] + dp[p][j - 1] * diff) % MOD
}
}
}
var ans = 0Lfor (i in k - 1 until n) ans = (ans + dp[i][k]) % MOD
return ans.toInt()
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
classSolution:
defsumOfPowers(self, nums: list[int], k: int) -> int:
MOD =10**9+7 n = len(nums)
nums.sort()
dp = [[0] * (k +1) for _ in range(n +1)]
for i in range(n):
dp[i][1] =1for j in range(2, k +1):
for i in range(j -1, n):
for p in range(j -2, i):
diff = nums[i] - nums[p]
dp[i][j] = (dp[i][j] + dp[p][j -1] * diff) % MOD
ans =0for i in range(k -1, n):
ans = (ans + dp[i][k]) % MOD
return ans
impl Solution {
pubfnsum_of_powers(nums: Vec<i32>, k: i32) -> i32 {
constMOD: i64=1_000_000_007;
let n = nums.len();
let k = k asusize;
letmut nums = nums;
nums.sort();
letmut dp =vec![vec![0i64; k +1]; n +1];
for i in0..n { dp[i][1] =1; }
for j in2..=k {
for i in j -1..n {
for p in j -2..i {
let diff = (nums[i] - nums[p]) asi64;
dp[i][j] = (dp[i][j] + dp[p][j -1] * diff) %MOD;
}
}
}
letmut ans =0i64;
for i in k -1..n {
ans = (ans + dp[i][k]) %MOD;
}
ans asi32 }
}