Sum of Subsequence Widths - Problem
Imagine you have an array of integers, and you want to explore all possible subsequences (sequences formed by removing some or no elements while maintaining order). Each subsequence has a width - the difference between its maximum and minimum elements.
Your task is to find the sum of widths of all non-empty subsequences.
Example: For array [2, 1, 3], the subsequences are:
[2]→ width = 2 - 2 = 0[1]→ width = 1 - 1 = 0[3]→ width = 3 - 3 = 0[2, 1]→ width = 2 - 1 = 1[2, 3]→ width = 3 - 2 = 1[1, 3]→ width = 3 - 1 = 2[2, 1, 3]→ width = 3 - 1 = 2
Total sum = 0 + 0 + 0 + 1 + 1 + 2 + 2 = 6
Since the answer can be very large, return it modulo 109 + 7.
Input & Output
example_1.py — Basic Case
$
Input:
[2, 1, 3]
›
Output:
6
💡 Note:
Subsequences: [2]→0, [1]→0, [3]→0, [2,1]→1, [2,3]→1, [1,3]→2, [2,1,3]→2. Sum = 6
example_2.py — Single Element
$
Input:
[1]
›
Output:
0
💡 Note:
Only one subsequence [1] with width = 1-1 = 0
example_3.py — Two Elements
$
Input:
[5, 3]
›
Output:
4
💡 Note:
Subsequences: [5]→0, [3]→0, [5,3]→2. Sum = 4 (after modulo, but result is small)
Constraints
- 1 ≤ nums.length ≤ 2 × 104
- -105 ≤ nums[i] ≤ 105
- Return result modulo 109 + 7
Visualization
Tap to expand
Understanding the Visualization
1
Sort Musicians by Height
Arrange in ascending order to establish clear max/min relationships
2
Calculate Individual Contributions
Each person contributes positively when tallest in group, negatively when shortest
3
Sum All Contributions
Add up positive and negative contributions to get total visual impact
Key Takeaway
🎯 Key Insight: Mathematical optimization transforms an exponential brute force problem into O(n log n) by calculating each element's net contribution across all subsequences.
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code