Find the Sum of Subsequence Powers - Problem
Find the Sum of Subsequence Powers
You're given an integer array
The power of a subsequence is defined as the minimum absolute difference between any two elements in that subsequence. For example, if we have a subsequence
Goal: Return the sum of powers of all subsequences that have exactly
Note: A subsequence maintains the relative order of elements from the original array but doesn't need to be contiguous.
You're given an integer array
nums of length n and a positive integer k. Your task is to find all possible subsequences of length k and calculate their "power" values.The power of a subsequence is defined as the minimum absolute difference between any two elements in that subsequence. For example, if we have a subsequence
[1, 5, 3], the power would be min(|1-5|, |1-3|, |5-3|) = min(4, 2, 2) = 2.Goal: Return the sum of powers of all subsequences that have exactly
k elements. Since the answer can be very large, return it modulo 10^9 + 7.Note: A subsequence maintains the relative order of elements from the original array but doesn't need to be contiguous.
Input & Output
example_1.py โ Basic Case
$
Input:
nums = [1, 2, 3, 4], k = 3
โบ
Output:
4
๐ก Note:
All 3-element subsequences: [1,2,3] (power=1), [1,2,4] (power=1), [1,3,4] (power=1), [2,3,4] (power=1). Sum = 1+1+1+1 = 4
example_2.py โ Different Powers
$
Input:
nums = [2, 2], k = 2
โบ
Output:
0
๐ก Note:
Only one 2-element subsequence: [2,2]. The power is |2-2| = 0. Sum = 0
example_3.py โ Single Element
$
Input:
nums = [4, 3, -1], k = 1
โบ
Output:
0
๐ก Note:
Single element subsequences have no pairs to compare, so power is undefined (we return 0 by convention)
Constraints
-
2 โค
nums.lengthโค 50 -
1 โค
kโคnums.length -
-108 โค
nums[i]โค 108 - The answer should be returned modulo 109 + 7
Visualization
Tap to expand
Understanding the Visualization
1
Identify Subsequences
Find all possible subsequences of length k
2
Calculate Powers
For each subsequence, find minimum absolute difference between any two elements
3
Sum All Powers
Add up all the power values to get the final result
Key Takeaway
๐ฏ Key Insight: Instead of generating all possible subsequences (exponential time), sort the array first and use dynamic programming to count subsequences with specific minimum differences, dramatically reducing time complexity.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code