1294. Product Cap Pairs
A lab records sensor readings in the array nums, sorted in non-decreasing order; readings can be negative, zero or positive. Two readings at different positions are considered compatible when their product does not exceed cap. Return the number of index pairs (i, j) with i < j whose readings are compatible. Equal values at different positions are different readings. The result and the products can be large, so use 64-bit integers.
Aim for O(n log n) time and O(1) extra space, where n is the length of nums: the sign of the left reading decides whether the products grow or shrink along the array, so each reading can binary search its partner range.
Example 1
- Input:
- nums = [-2,-1,0,3], cap = 0
- Output:
- 5
- Explanation:
The pairs with product at most 0 are (-2,0), (-2,3), (-1,0), (-1,3) and (0,3), which makes 5.
Example 2
- Input:
- nums = [1,2,3], cap = 3
- Output:
- 2
- Explanation:
The products are 2, 3 and 6, and only 2 and 3 are at most 3, so there are 2 pairs.
Example 3
- Input:
- nums = [-3,-2,4], cap = -6
- Output:
- 2
- Explanation:
(-3,-2) has product 6, which is above -6, while (-3,4) = -12 and (-2,4) = -8 are both at most -6.
Constraints
1 ≤ nums.length ≤ 1000
-105 ≤ nums[i] ≤ 105, sorted non-decreasing
-1010 ≤ cap ≤ 1010
How this problem is judged
- Answers
- Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
Expected complexity
- Time
- O(n log n)
- Space
- O(1)