Ctrl K

Sum of Segment Minimums

Medium
You are given an array of positive integers values. Consider every non-empty segment of it, that is, every run of consecutive elements. Take the smallest element of each segment and add those minimums up. The sum can be very large, so return it modulo 10⁹ + 7. Trying every segment takes O(n²); aim for O(n).
Example 1
values=[2, 5, 1] → 12

The segments are [2], [5], [1], [2, 5], [5, 1] and [2, 5, 1]. Their minimums 2, 5, 1, 2, 1, 1 add up to 12.

Example 2
values=[3, 3] → 9

The segments [3], [3] and [3, 3] each have minimum 3, for a total of 9.

Constraints
  • 1 ≤ len(values) ≤ 3 · 10⁴
  • 1 ≤ values[i] ≤ 3 · 10⁴
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsTree of Leaf Products MediumAll-Ones Rectangles MediumCheapest Hop Route MediumHopping Along the Stones MediumWater Between Walls Hard
loading Python…
Input
values=[2, 5, 1]
Expected
12

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