LeetCode 2892: Minimizing Array After Replacing Pairs With Their Product
Problem Description
Explanation:
To solve this problem, we can iterate over the array in pairs, calculate the product of each pair, and replace the pair with its product. We continue this process until we reach the end of the array. The goal is to minimize the sum of the array after all replacements.
Algorithm:
- Iterate over the array in pairs from index 0 to n-1, where n is the size of the array.
- Calculate the product of the pair (arr[i], arr[i+1]) and replace the pair with this product.
- Continue this process until reaching the end of the array.
- Finally, return the sum of the array elements.
Time Complexity: O(n) Space Complexity: O(1)
:
Solutions
class Solution {
public int minSumOfLengths(int[] arr) {
int n = arr.length;
int[] dp = new int[n];
Arrays.fill(dp, Integer.MAX_VALUE);
int sum = 0, result = Integer.MAX_VALUE, minSoFar = Integer.MAX_VALUE;
for (int i = 0, j = 0; j < n; j++) {
sum += arr[j];
while (sum > arr[j]) {
sum -= arr[i++];
}
if (sum == arr[j]) {
int currLen = j - i + 1;
if (i > 0 && dp[i - 1] != Integer.MAX_VALUE) {
result = Math.min(result, dp[i - 1] + currLen);
}
minSoFar = Math.min(minSoFar, currLen);
}
dp[j] = minSoFar;
}
return result == Integer.MAX_VALUE ? -1 : result;
}
}
Loading editor...