Ctrl K

Spread Over All Selections

Hard
The spread of a collection of numbers is the difference between its largest and smallest elements. You are given an array values. Consider all of its non-empty subsequences: collections obtained by crossing out any elements (possibly none) while keeping the rest in order. Selections taken from different positions count separately, even if their values match. Return the sum of the spreads of all these selections modulo 10⁹ + 7.
Example 1
values=[5, 1, 4] → 12

Single-element selections have spread 0. Pairs: {5, 1} → 4, {5, 4} → 1, {1, 4} → 3. The whole array: 5 − 1 = 4. Total: 4 + 1 + 3 + 4 = 12.

Example 2
values=[7, 7] → 0

Every selection has equal maximum and minimum, so the answer is 0.

Example 3
values=[3] → 0
Constraints
  • 1 ≤ len(values) ≤ 10⁵
  • 1 ≤ values[i] ≤ 10⁵
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsWhere the Friends Should Meet HardBiggest Number Divisible by Three HardParcel Lockers Along a Road HardBest View for a Turning Camera HardTallest House Under Height Caps Hard
loading Python…
Input
values=[5, 1, 4]
Expected
12

Run checks the first 3 tests in your browser. Submit checks all 87 tests on the server, hidden ones included.