Skip to content

Instantly share code, notes, and snippets.

@rayjcwu
Last active August 29, 2015 13:57
Show Gist options
  • Save rayjcwu/9926885 to your computer and use it in GitHub Desktop.
Save rayjcwu/9926885 to your computer and use it in GitHub Desktop.
public int countPair(int[] A, int X) {
int small = 0;
int big = 0;
int count = 0;
// find max big such that A[0] + A[big] <= X
while (big + 1 < A.length && A[0] + A[big + 1] <= X) {
big++;
}
// count use A[small] as smallest number, A[small + 1: big] as bigger number
while (big > small) {
if (A[small] + A[big] <= X) {
count += big - small;
small++;
} else /* A[small] + A[big] > X */ {
big--;
}
}
return count;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment