Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.*;
- class Solution {
- public int solve(List<Integer> price, int a, int b) {
- Collections.sort(price);
- int count = 0;
- int n = price.size();
- for (int i = 0; i < n; i++) {
- int target1 = a - price.get(i);
- int target2 = b - price.get(i);
- int left = i + 1;
- int right = n - 1;
- int lowerBound = lowerBound(price, left, right, target1);
- int upperBound = upperBound(price, left, right, target2);
- count += upperBound - lowerBound + 1;
- }
- return count;
- }
- private int lowerBound(List<Integer> price, int left, int right, int target) {
- while (left <= right) {
- int mid = left + (right - left) / 2;
- if (price.get(mid) >= target) {
- right = mid - 1;
- } else {
- left = mid + 1;
- }
- }
- return left;
- }
- private int upperBound(List<Integer> price, int left, int right, int target) {
- while (left <= right) {
- int mid = left + (right - left) / 2;
- if (price.get(mid) > target) {
- right = mid - 1;
- } else {
- left = mid + 1;
- }
- }
- return right;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement