[LeetCode] Minimizing Array After Replacing Pairs With Their Product

2892. Minimizing Array After Replacing Pairs With Their Product

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 (e.g. in one operation the array [1, 2, 2, 3] with k = 5 can 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.

1
2
3
4
5
6
7
8
9
10
11
12
13
class Solution {
public:
int minArrayLength(vector<int>& nums, int k) {
int res = 0, p = 0;
while(p < nums.size()) {
long long x = nums[p++];
while(p < nums.size() and x * nums[p] <= k) x *= nums[p++];
res += 1;
if(x == 0) return 1;
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2023/10/09/PS/LeetCode/minimizing-array-after-replacing-pairs-with-their-product/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.