LeetCode 2552. Count Increasing Quadruplets Solution in Java, C++, Python & Go | Explanation + Code

CoderIndeed
0
2552. Count Increasing Quadruplets

Description

Given a 0-indexed integer array nums of size n containing all numbers from 1 to n, return the number of increasing quadruplets.

A quadruplet (i, j, k, l) is increasing if:

  • 0 <= i < j < k < l < n, and
  • nums[i] < nums[k] < nums[j] < nums[l].

 

Example 1:

Input: nums = [1,3,2,4,5]
Output: 2
Explanation: 
- When i = 0, j = 1, k = 2, and l = 3, nums[i] < nums[k] < nums[j] < nums[l].
- When i = 0, j = 1, k = 2, and l = 4, nums[i] < nums[k] < nums[j] < nums[l]. 
There are no other quadruplets, so we return 2.

Example 2:

Input: nums = [1,2,3,4]
Output: 0
Explanation: There exists only one quadruplet with i = 0, j = 1, k = 2, l = 3, but since nums[j] < nums[k], we return 0.

 

Constraints:

  • 4 <= nums.length <= 4000
  • 1 <= nums[i] <= nums.length
  • All the integers of nums are unique. nums is a permutation.

Solutions

Solution 1: Enumeration + Preprocessing

We can enumerate j and k in the quadruplet, then the problem is transformed into, for the current j and k:

  • Count how many l satisfy l > k and nums[l] > nums[j];
  • Count how many i satisfy i < j and nums[i] < nums[k].

We can use two two-dimensional arrays f and g to record these two pieces of information. Where f[j][k] represents how many l satisfy l > k and nums[l] > nums[j], and g[j][k] represents how many i satisfy i < j and nums[i] < nums[k].

Therefore, the answer is the sum of all f[j][k] × g[j][k].

The time complexity is O(n2), and the space complexity is O(n2). Where n is the length of the array.

PythonJavaC++Go
class Solution: def countQuadruplets(self, nums: List[int]) -> int: n = len(nums) f = [[0] * n for _ in range(n)] g = [[0] * n for _ in range(n)] for j in range(1, n - 2): cnt = sum(nums[l] > nums[j] for l in range(j + 1, n)) for k in range(j + 1, n - 1): if nums[j] > nums[k]: f[j][k] = cnt else: cnt -= 1 for k in range(2, n - 1): cnt = sum(nums[i] < nums[k] for i in range(k)) for j in range(k - 1, 0, -1): if nums[j] > nums[k]: g[j][k] = cnt else: cnt -= 1 return sum( f[j][k] * g[j][k] for j in range(1, n - 2) for k in range(j + 1, n - 1) )(code-box)

Post a Comment

0Comments

Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Check Now
Accept !