Given a 0-indexed integer array nums
of length n
and an integer target
, return the number of pairs (i, j)
where 0 <= i < j < n
and nums[i] + nums[j] < target
.
LeetCode Problem - 2824
// This is a Java class named Solution.
class Solution {
public int countPairs(List<Integer> nums, int target) {
// Initialize a variable 'count' to keep track of the number of pairs.
int count = 0;
// Iterate through each element at index 'i' in the 'nums' list.
for(int i=0; i<nums.size(); i++){
// Iterate through each element at index 'j' starting from 'i+1' to the end of the list.
for(int j=i+1; j<nums.size(); j++){
// Check if the sum of the elements at index 'i' and 'j' is less than 'target'.
// If so, increment the 'count' as it represents a valid pair.
if((nums.get(i) + nums.get(j)) < target){
count++;
}
}
}
// Return the total count of pairs whose sum is less than 'target'.
return count;
}
}