Minimizing Array After Replacing Pairs With Their Product - Problem
Given an integer array nums and an integer k, you can perform a special merge operation any number of times. In each operation, you can select two adjacent elements x and y where x * y ≤ k, and replace both elements with their product x * y.

For example, with array [1, 2, 2, 3] and k = 5:
• You can merge the first two elements: [1, 2, 2, 3] → [2, 2, 3]
• Or merge elements at positions 1 and 2: [1, 2, 2, 3] → [1, 4, 3]
• But you cannot merge the last two elements since 2 * 3 = 6 > 5

Your goal is to find the minimum possible length of the array after performing any number of these operations strategically.

Input & Output

example_1.py — Basic merge operations
$ Input: nums = [1, 2, 2, 3], k = 5
Output: 2
💡 Note: We can merge [1,2] to get [2,2,3], then merge [2,2] to get [4,3]. Since 4*3=12 > 5, we cannot merge further. Final array: [4,3] with length 2.
example_2.py — No merges possible
$ Input: nums = [3, 4, 5], k = 6
Output: 3
💡 Note: No adjacent pairs can be merged since 3*4=12>6, 4*5=20>6. The array remains [3,4,5] with length 3.
example_3.py — Complete merge possible
$ Input: nums = [1, 1, 2, 2], k = 10
Output: 1
💡 Note: We can merge the entire array: [1,1,2,2] → [1,2,2] → [2,2] → [4]. The product 1*1*2*2=4 ≤ 10, so we get length 1.

Constraints

  • 1 ≤ nums.length ≤ 20
  • 1 ≤ nums[i] ≤ 105
  • 1 ≤ k ≤ 109
  • Adjacent elements only: Can only merge consecutive elements in the array

Visualization

Tap to expand
Optimal Array Partitioning StrategyExample: [1, 2, 2, 3] with k = 5Original Array1223Segment 1[1,2,2] → 4 ≤ 5 ✓Segment 2[3] → 3 ≤ 5 ✓43Final Result: Array length = 2Cannot merge further since 4 × 3 = 12 > 5
Understanding the Visualization
1
Identify Segments
Find all possible segments that can be merged completely
2
Dynamic Programming
Use DP to find minimum partitioning into valid segments
3
Optimal Solution
The DP solution gives us the minimum possible array length
Key Takeaway
🎯 Key Insight: The problem reduces to finding the optimal way to partition the array into segments where each segment can be completely merged, minimizing the total number of segments.
Asked in
Google 35 Amazon 28 Microsoft 22 Meta 18
32.4K Views
Medium Frequency
~25 min Avg. Time
847 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