You are given an integer array nums
of length n
, and a positive integer k
. The power of a subsequence is defined as the minimum absolute difference between any two elements in the subsequence. Return the sum of powers of all subsequences of nums
which have length equal to k
. Since the answer may be large, return it modulo 10^9 + 7
.
For example:
nums = [1,2,3,4], k = 3
. The subsequences are [1,2,3]
, [1,3,4]
, [1,2,4]
, and [2,3,4]
. The powers are 1
, 1
, 1
, and 1
respectively. The sum of the powers is 4
.nums = [2,2], k = 2
. The only subsequence is [2,2]
. The power is 0
.nums = [4,3,-1], k = 2
. The subsequences are [4,3]
, [4,-1]
, and [3,-1]
. The powers are 1
, 5
, and 4
respectively. The sum of the powers is 10
.Constraints:
2 <= n == nums.length <= 50
-10^8 <= nums[i] <= 10^8
2 <= k <= n
The most straightforward approach is to generate all possible subsequences of length k
from the input array nums
, calculate the power (minimum absolute difference between any two elements) for each subsequence, and then sum up these powers.
This involves:
k
elements from nums
.from itertools import combinations
def calculate_power(subsequence):
min_diff = float('inf')
for i in range(len(subsequence)):
for j in range(i + 1, len(subsequence)):
min_diff = min(min_diff, abs(subsequence[i] - subsequence[j]))
return min_diff
def sum_of_powers_brute_force(nums, k):
subsequences = combinations(nums, k)
total_power = 0
for sub in subsequences:
total_power = (total_power + calculate_power(sub)) % (10**9 + 7)
return total_power
combinations
function in itertools
creates an iterator, so it doesn't store all combinations in memory at once, but the algorithm still needs to iterate through them. The space used is dominated by the size of the subsequences being processed, which contributes to an effective space complexity related to the number of combinations in flight.The key optimization is to realize that we only need to consider adjacent elements after sorting the subsequence. Here's how it works:
k
.from itertools import combinations
def sum_of_powers_optimal(nums, k):
nums.sort()
total_power = 0
for sub in combinations(nums, k):
min_diff = float('inf')
for i in range(len(sub) - 1):
min_diff = min(min_diff, abs(sub[i] - sub[i+1]))
total_power = (total_power + min_diff) % (10**9 + 7)
return total_power