LeetCode 2426: Number of Pairs Satisfying Inequality

Problem Description

Explanation:

To solve this problem, we can iterate through each pair of indices (i, j) where 0 <= i < j <= n - 1 and check if the given condition nums1[i] - nums1[j] <= nums2[i] - nums2[j] + diff holds true. If it does, we increment a counter to keep track of the number of valid pairs. We can optimize this solution by rearranging the inequality to nums1[i] - nums2[i] <= nums1[j] - nums2[j] + diff and then comparing the differences between the corresponding elements in the arrays.

Detailed Steps:

  1. Initialize a counter variable count to 0.
  2. Iterate through each pair of indices (i, j) where 0 <= i < j <= n - 1.
  3. For each pair of indices, check if nums1[i] - nums2[i] <= nums1[j] - nums2[j] + diff.
  4. If the condition is satisfied, increment count.
  5. Return the final count of valid pairs.

Time Complexity: O(n) where n is the number of elements in the input arrays. Space Complexity: O(1) since we are using a constant amount of extra space.

:

Solutions

class Solution {
    public int countPairs(int[] nums1, int[] nums2, int diff) {
        int count = 0;
        int n = nums1.length;
        
        for (int i = 0; i < n; i++) {
            for (int j = i + 1; j < n; j++) {
                if (nums1[i] - nums2[i] <= nums1[j] - nums2[j] + diff) {
                    count++;
                }
            }
        }
        
        return count;
    }
}

Loading editor...