Skip to content

2824. Count Pairs Whose Sum is Less than Target 👍

  • Time: $O(n^2)$
  • Space: $O(1)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
class Solution {
 public:
  int countPairs(vector<int>& nums, int target) {
    int ans = 0;

    for (int i = 0; i < nums.size(); ++i)
      for (int j = i + 1; j < nums.size(); ++j)
        if (nums[i] + nums[j] < target)
          ++ans;

    return ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
class Solution {
  public int countPairs(List<Integer> nums, int target) {
    int ans = 0;

    for (int i = 0; i < nums.size(); ++i)
      for (int j = i + 1; j < nums.size(); ++j)
        if (nums.get(i) + nums.get(j) < target)
          ++ans;

    return ans;
  }
}
1
2
3
4
5
class Solution:
  def countPairs(self, nums: list[int], target: int) -> int:
    return sum(nums[i] + nums[j] < target
               for i in range(len(nums))
               for j in range(i + 1, len(nums)))