Skip to content

1099. Two Sum Less Than K 👍

  • Time: $O(n)$
  • Space: $O(1)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Solution {
 public:
  int twoSumLessThanK(vector<int>& A, int K) {
    if (A.size() < 2)
      return -1;

    int ans = -1;  // note the constraint that A[i] > 0
    int l = 0;
    int r = A.size() - 1;

    sort(begin(A), end(A));

    while (l < r)
      if (A[l] + A[r] < K) {
        ans = max(ans, A[l] + A[r]);
        ++l;
      } else {
        --r;
      }

    return ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution {
  public int twoSumLessThanK(int[] A, int K) {
    if (A.length < 2)
      return -1;

    int ans = -1; // note the constraint that A[i] > 0
    int l = 0;
    int r = A.length - 1;

    Arrays.sort(A);

    while (l < r)
      if (A[l] + A[r] < K) {
        ans = Math.max(ans, A[l] + A[r]);
        ++l;
      } else {
        --r;
      }

    return ans;
  }
}