Minimizing Array After Replacing Pairs With Their Product Problem
#2892
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 2892.
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
xandy, 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 = 5can become[1, 4, 3]or[2, 2, 3], but can't become[1, 2, 6]).
Return the minimum possible length of nums after any number of operations.
Example 1:
Input: nums = [2,3,3,7,3,5], k = 20
Output: 3
Explanation: We perform these operations:
1. [2,3,3,7,3,5] -> [6,3,7,3,5]
2. [6,3,7,3,5] -> [18,7,3,5]
3. [18,7,3,5] -> [18,7,15]
It can be shown that 3 is the minimum length possible to achieve with the given operation.
Example 2:
Input: nums = [3,3,3,3], k = 6
Output: 4
Explanation: We can't perform any operations since the product of every two adjacent elements is greater than 6.
Hence, the answer is 4.
Constraints:
1 <= nums.length <= 10^50 <= nums[i] <= 10^91 <= k <= 10^9
Solution
Approach: Greedy
Scan from left to right, keeping the length so far ans (starting at 1) and the product y of the current block (starting at nums[0]). For each next element x:
- If
x = 0, merging everything gives product0 <= k, so the answer is1. - If
x * y <= k, mergexinto the block:y = x * y. - Otherwise start a new block:
y = xandans = ans + 1.
Making each block as long as possible is optimal, so the greedy gives the minimum length.
Complexity: time O(n), space O(1), where n is the length of the array.
class Solution:
def minArrayLength(self, nums: List[int], k: int) -> int:
ans, y = 1, nums[0]
for x in nums[1:]:
if x == 0:
return 1
if x * y <= k:
y *= x
else:
y = x
ans += 1
return ans