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
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code