Find the Sum of Subsequence Powers - Problem

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.

Input & Output

Example 1 — Basic Case
$ Input: nums = [1,2,3,4], k = 3
Output: 4
💡 Note: All subsequences of length 3: [1,2,3] (min diff = 1), [1,2,4] (min diff = 1), [1,3,4] (min diff = 1), [2,3,4] (min diff = 1). Sum = 1+1+1+1 = 4
Example 2 — Different Powers
$ Input: nums = [2,2], k = 2
Output: 0
💡 Note: Only one subsequence [2,2] with minimum absolute difference |2-2| = 0. Sum = 0
Example 3 — Single Element
$ Input: nums = [10,7,3], k = 1
Output: 0
💡 Note: When k=1, subsequences have only one element, so no pairs exist to calculate differences. Sum = 0

Constraints

  • 2 ≤ nums.length ≤ 50
  • 1 ≤ nums[i] ≤ 50
  • 2 ≤ k ≤ nums.length

Visualization

Tap to expand
Sum of Subsequence Powers INPUT nums array: 1 2 3 4 i=0 i=1 i=2 i=3 k = 3 (subsequence length) n = 4 (array length) All k=3 Subsequences: [1,2,3] [1,2,4] [1,3,4] [2,3,4] power = 1 power = 1 power = 1 power = 1 MOD = 10^9 + 7 ALGORITHM STEPS 1 Sort Array Sort to find adjacent min differences easily 2 DP with State dp[i][cnt][minDiff] Track position, count, min diff in subsequence 3 Enumerate Subseqs For each element: - Include or skip - Update min diff 4 Sum Powers When cnt == k: Add minDiff to result power([1,2,3]) = min(|2-1|, |3-2|, |3-1|) = 1 Minimum absolute difference FINAL RESULT Computing each subsequence: [1,2,3] min diff = 1, power = 1 [1,2,4] min diff = 1, power = 1 [1,3,4] min diff = 1, power = 1 [2,3,4] min diff = 1, power = 1 Sum = 1 + 1 + 1 + 1 OUTPUT 4 OK Key Insight: The power of a subsequence is its MINIMUM absolute difference. Sorting the array first allows efficient DP: for a sorted subsequence, min diff is always between adjacent elements. Use memoization with states (index, count, current_min_diff) to avoid recalculating. Time: O(n^4 * d) where d = distinct diffs. TutorialsPoint - Find the Sum of Subsequence Powers | Optimal DP Solution
Asked in
Google 15 Facebook 12 Amazon 8
8.5K Views
Medium Frequency
~35 min Avg. Time
234 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen