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 After Replacing Pairs INPUT Array: nums 2 3 5 4 [0] [1] [2] [3] k = 10 max product limit Merge adjacent pairs where x * y <= k Goal: Minimize array length Initial length: 4 ALGORITHM STEPS 1 Check [2,3] 2*3=6 <= 10 [OK] Merge to [6,5,4] 2 Check [6,5] 6*5=30 > 10 [NO] Cannot merge 3 Check [5,4] 5*4=20 > 10 [NO] Cannot merge 4 Final Array No more merges Result: [6,5,4] Greedy Merge Process: [2,3,5,4] --> [6,5,4] Scan left to right FINAL RESULT Minimized Array: 6 5 4 [0] [1] [2] Output: 3 Minimum Length Verification: Original: [2,3,5,4] After merge: [6,5,4] Length reduced: 4 --> 3 Status: [OK] Optimal Key Insight: Greedy left-to-right merging works because merging earlier pairs may create opportunities for further merges. Always check if x*y <= k before merging adjacent elements. Time complexity: O(n) where n is the array length. TutorialsPoint - Minimizing Array After Replacing Pairs With Their Product | Greedy - Left to Right Merging
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