Skip to content

Latest commit

 

History

History

2426

Folders and files

NameName
Last commit message
Last commit date

parent directory

..
 
 

You are given two 0-indexed integer arrays nums1 and nums2, each of size n, and an integer diff. Find the number of pairs (i, j) such that:

  • 0 <= i < j <= n - 1 and
  • nums1[i] - nums1[j] <= nums2[i] - nums2[j] + diff.

Return the number of pairs that satisfy the conditions.

 

Example 1:

Input: nums1 = [3,2,5], nums2 = [2,2,1], diff = 1
Output: 3
Explanation:
There are 3 pairs that satisfy the conditions:
1. i = 0, j = 1: 3 - 2 <= 2 - 2 + 1. Since i < j and 1 <= 1, this pair satisfies the conditions.
2. i = 0, j = 2: 3 - 5 <= 2 - 1 + 1. Since i < j and -2 <= 2, this pair satisfies the conditions.
3. i = 1, j = 2: 2 - 5 <= 2 - 1 + 1. Since i < j and -3 <= 2, this pair satisfies the conditions.
Therefore, we return 3.

Example 2:

Input: nums1 = [3,-1], nums2 = [-2,2], diff = -1
Output: 0
Explanation:
Since there does not exist any pair that satisfies the conditions, we return 0.

 

Constraints:

  • n == nums1.length == nums2.length
  • 2 <= n <= 105
  • -104 <= nums1[i], nums2[i] <= 104
  • -104 <= diff <= 104

Companies: Google

Related Topics:
Array, Binary Search, Divide and Conquer, Binary Indexed Tree, Segment Tree, Merge Sort, Ordered Set

Similar Questions:

Solution 1. Merge Sort

A[i] - A[j] <= B[i] - B[j] + diff

A[i] - B[i] <= A[j] - B[j] + diff

Let C[i] = A[i] - B[i]

C[i] <= C[j] + diff

This is similar to 493. Reverse Pairs (Hard). We can use Merge Sort (Divide and Conquer) to solve it.

// OJ: https://leetcode.com/problems/number-of-pairs-satisfying-inequality
// Author: github.com/lzl124631x
// Time: O(NlogN)
// Space: O(N)
class Solution {
public:
    long long numberOfPairs(vector<int>& A, vector<int>& B, int diff) {
        long long N = A.size(), ans = 0;
        for (int i = 0; i < N; ++i) A[i] -= B[i];
        function<void(int, int)> merge = [&](int start, int end) {
            if (start + 1 >= end) return;
            int mid = (start + end) / 2;
            merge(start, mid);
            merge(mid, end);
            for (int i = start, j = mid, k = start, t = start; k < end; ++k) {
                if (j == end || (i < mid && A[i] <= A[j])) B[k] = A[i++];
                else {
                    while (t < mid && A[t] <= A[j] + diff) ++t;
                    ans += t - start;
                    B[k] = A[j++];
                }
            }
            for (int i = start; i < end; ++i) A[i] = B[i];
        };
        merge(0, N);
        return ans;
    }
};