Ctrl K

Best Varied Window

Medium
You get an array of positive integers values and two integers min_distinct and width. A window is a run of consecutive elements of length exactly width. A window is varied if it contains at least min_distinct different values. Return the largest sum among varied windows. If there is no varied window, return 0.
Example 1
values=[4, 4, 9, 1, 9, 9], min_distinct=2, width=3 → 19

Windows: [4, 4, 9] = 17, [4, 9, 1] = 14, [9, 1, 9] = 19, [1, 9, 9] = 19. All have at least two distinct values; the best is 19.

Example 2
values=[3, 3, 3, 3], min_distinct=2, width=2 → 0

Every window holds only 3s, so none qualifies and the answer is 0.

Example 3
values=[8, 2, 8, 5, 7], min_distinct=3, width=4 → 23

[8, 2, 8, 5] has three distinct values and sums to 23; [2, 8, 5, 7] has four and sums to 22. The answer is 23.

Constraints
  • 1 ≤ len(values) ≤ 10⁵
  • 1 ≤ min_distinct ≤ width ≤ len(values)
  • 1 ≤ values[i] ≤ 10⁹
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsTwo-Genre Stretch of a Playlist MediumWindows With an Exact Alarm Count MediumStretches With k Odd Numbers MediumTwo Separate Segments With a Given Sum MediumTrim the Ends to a Target Medium
loading Python…
Input
values=[4, 4, 9, 1, 9, 9], min_distinct=2, width=3
Expected
19

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