Sum of Subsequence Widths - Problem
The width of a sequence is the difference between the maximum and minimum elements in the sequence.
Given an array of integers nums, return the sum of the widths of all the non-empty subsequences of nums. Since the answer may be very large, return it modulo 10^9 + 7.
A subsequence is a sequence that can be derived from an array by deleting some or no elements without changing the order of the remaining elements. For example, [3,6,2,7] is a subsequence of the array [0,3,1,6,2,2,7].
Input & Output
Example 1 — Basic Case
$
Input:
nums = [2,1,3]
›
Output:
6
💡 Note:
All subsequences: [2]→0, [1]→0, [3]→0, [2,1]→1, [2,3]→1, [1,3]→2, [2,1,3]→2. Sum = 0+0+0+1+1+2+2 = 6
Example 2 — Single Element
$
Input:
nums = [5]
›
Output:
0
💡 Note:
Only one subsequence [5] with width = 5-5 = 0
Example 3 — Two Elements
$
Input:
nums = [1,4]
›
Output:
6
💡 Note:
Subsequences: [1]→0, [4]→0, [1,4]→3. Sum = 0+0+3 = 3. Wait, let me recalculate: [1,4]→4-1=3. Total = 3
Constraints
- 1 ≤ nums.length ≤ 20000
- -104 ≤ nums[i] ≤ 104
Visualization
Tap to expand
Understanding the Visualization
1
Input
Array [2, 1, 3] with all possible subsequences
2
Calculate Widths
Find max-min for each subsequence
3
Sum Results
Add all widths: 0+0+0+1+1+2+2 = 6
Key Takeaway
🎯 Key Insight: After sorting, each element's contribution can be calculated mathematically using powers of 2
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code