You are given an array nums[], which is divided into two parts. Each part is individually sorted in ascending order. Your task is to determine the number of reverse pairs, which are defined as (i, j) where:
Input: nums[]=[3,4,6,11,1,12,15]Output: 6Explanation:
- First part:[3,4,6,11]- Second part:[1,12,15]Reverse pairs:(3,1),(4,1),(6,1),(11,1),(3,12), and (4,12).Total =6 pairs.
publicclassSolution {
publicintcountReversePairs(int[] nums, int divisionPoint) {
int count = 0;
// Define pointers for both parts of the arrayint i = 0; // Pointer for first partint j = divisionPoint; // Pointer for second part// Traverse through both parts of the arraywhile (i < divisionPoint && j < nums.length) {
if (nums[i]> nums[j]) {
// Count the reverse pairs starting from j to the end count += (nums.length- j);
i++;
} else {
j++;
}
}
return count;
}
publicstaticvoidmain(String[] args) {
Solution solution =new Solution();
int[] nums = {1, 5, 7, 10, 2, 6, 8};
int divisionPoint = 4; // First part ends, second part begins System.out.println(solution.countReversePairs(nums, divisionPoint)); // Output: 7 }
}
classSolution:
defcountReversePairs(self, nums, division_point):
count =0 i, j =0, division_point # Pointers for two parts of the array n = len(nums)
while i < division_point and j < n:
if nums[i] > nums[j]:
# Count all pairs for current `nums[i]` in the second part count += n - j
i +=1else:
j +=1return count
# Examplessolution = Solution()
nums = [1, 5, 7, 10, 2, 6, 8]
division_point =4# First part ends, second part beginsprint(solution.countReversePairs(nums, division_point)) # Output: 7
Move j backward to the previous valid pairs: Reset as moving
Let’s correct and systematically dry-run from where I stopped to clarify reverse pair count progressively!