LeetCode 2552: Count Increasing Quadruplets
Problem Description
Explanation
To solve this problem, we can iterate through the given array nums
and maintain two arrays left
and right
. The left
array stores the count of increasing subarrays ending at index i
such that nums[i]
is the smallest element, and the right
array stores the count of increasing subarrays starting at index i
such that nums[i]
is the largest element.
We then iterate through the array to calculate the total count of increasing quadruplets. For each index i
, we calculate the count of increasing quadruplets where nums[i]
is the second smallest element. This count is the product of left[i] * right[i]
.
Finally, we sum up the counts for all indices i
to get the total count of increasing quadruplets.
- Time complexity: O(n^2) where n is the length of the input array
nums
. - Space complexity: O(n) to store the
left
andright
arrays.
Solutions
class Solution {
public int countQuadruplets(int[] nums) {
int n = nums.length;
int[] left = new int[n];
int[] right = new int[n];
for (int i = 0; i < n; i++) {
for (int j = 0; j < i; j++) {
if (nums[j] < nums[i]) {
left[i]++;
}
}
}
for (int i = n - 1; i >= 0; i--) {
for (int j = n - 1; j > i; j--) {
if (nums[i] < nums[j]) {
right[i]++;
}
}
}
int quadruplets = 0;
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
quadruplets += left[i] * right[j];
}
}
return quadruplets;
}
}
Loading editor...