Ctrl K

Merging Neighbours Under a Cap

Medium
You are given an array of non-negative integers values and an integer cap. In one operation you may pick two adjacent elements a and b with a · b ≤ cap and replace them with a single element equal to a · b. You may perform any number of operations, including none. For example, with cap = 6 the array [1, 3, 2, 4] can become [3, 2, 4] or [1, 6, 4], but not [1, 3, 8]. Return the smallest length the array can be reduced to.
Example 1
values=[2, 5, 1, 3, 4], cap=12 → 2

[2, 5, 1, 3, 4] → [10, 1, 3, 4] → [10, 3, 4] → [10, 12]. 10 and 12 cannot merge: 120 > 12.

Example 2
values=[4, 0, 9, 9], cap=1 → 1

A zero merges with any neighbour into another zero, so the whole array collapses into one number.

Example 3
values=[5, 7], cap=30 → 2

5 · 7 = 35 > 30, so nothing can be merged.

Constraints
  • 1 ≤ len(values) ≤ 10⁵
  • 0 ≤ values[i] ≤ 10⁹
  • 1 ≤ cap ≤ 10⁹
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsFewest Jumps to the End MediumReach the Last Cell MediumAs Many Trades as You Like MediumLongest Seesaw Subsequence MediumFewest Meetings to Cancel Medium
loading Python…
Input
values=[2, 5, 1, 3, 4], cap=12
Expected
2

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