Minimizing Array After Replacing Pairs With Their Product - Problem

Given an integer array nums and an integer k, you can perform the following operation on the array any number of times:

Select two adjacent elements of the array like x and y, such that x * y <= k, and replace both of them with a single element with value x * y.

For example, in one operation the array [1, 2, 2, 3] with k = 5 can become [1, 4, 3] or [2, 2, 3], but cannot become [1, 2, 6] because 2 * 3 = 6 > 5.

Return the minimum possible length of nums after any number of operations.

Input & Output

Example 1 — Basic Case
$ Input: nums = [2,3,5,4], k = 10
Output: 3
💡 Note: We can merge 2×3=6 to get [6,5,4]. Cannot merge 6×5=30 > 10 or 5×4=20 > 10. Final length is 3.
Example 2 — Multiple Merges
$ Input: nums = [1,2,2,3], k = 5
Output: 2
💡 Note: Merge 1×2=2 to get [2,2,3]. Then merge 2×2=4 to get [4,3]. Cannot merge 4×3=12 > 5. Final length is 2.
Example 3 — No Merges Possible
$ Input: nums = [7,8,9], k = 10
Output: 3
💡 Note: 7×8=56 > 10 and 8×9=72 > 10. No adjacent pairs can be merged. Original length 3 remains.

Constraints

  • 1 ≤ nums.length ≤ 103
  • 1 ≤ nums[i] ≤ 105
  • 1 ≤ k ≤ 109

Visualization

Tap to expand
Minimizing Array: Merge Adjacent Pairs (k=10)Original Array:23542×3=6≤10 ✓5×4=20>10 ✗After Merge:6546×5=30>10 ✗5×4=20>10 ✗Final Length: 3 (No more merges possible)
Asked in
Google 15 Amazon 12 Microsoft 8
23.0K Views
Medium Frequency
~15 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen