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
andy
, such thatx * y <= k
, and replace both of them with a single element with valuex * y
(e.g. in one operation the array[1, 2, 2, 3]
withk = 5
can become[1, 4, 3]
or[2, 2, 3]
, but can’t become[1, 2, 6]
).
Return _theminimum possible length of _nums
after any number of operations.
Examples
Example 1:
|
|
Example 2:
|
|
Constraints:
1 <= nums.length <= 10^5
0 <= nums[i] <= 10^9
1 <= k <= 10^9
Solution
Method 1 – Greedy Dynamic Programming
Intuition
To minimize the array length, we want to merge as many adjacent pairs as possible, but only if their product does not exceed k. This is similar to interval merging, and can be solved using dynamic programming: for each subarray, compute the minimum length after all possible merges.
Approach
- Use DP where
dp[l][r]
is the minimum length for subarray nums[l:r+1]. - For each interval, try all possible splits, and if adjacent elements can be merged (product ≤ k), merge them and update the DP.
- Use memoization to avoid recomputation.
- The answer is
dp[0][n-1]
.
Code
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Complexity
- ⏰ Time complexity:
O(n^3)
- Triple nested loop for DP.
- 🧺 Space complexity:
O(n^2)
- For DP table.