
Problem Statement
In this problem, we are tasked with finding the maximum possible sum of two distinct elements from a given array of integers, such that this sum is less than a provided threshold k
. Specifically, we need to identify two indices i
and j
(with i < j
) where the sum of nums[i]
and nums[j]
is the highest possible under the constraint that it must be less than k
. If no such pair exists that conforms to these rules, the function should return -1
.
Examples
Example 1
Input:
nums = [34,23,1,24,75,33,54,8], k = 60
Output:
58
Explanation:
We can use 34 and 24 to sum 58 which is less than 60.
Example 2
Input:
nums = [10,20,30], k = 15
Output:
-1
Explanation:
In this case it is not possible to get a pair sum less that 15.
Constraints
1 <= nums.length <= 100
1 <= nums[i] <= 1000
1 <= k <= 2000
Approach and Intuition
To solve this problem, our goal is to maximize the sum of two numbers from the array while ensuring that their sum is less than the given limit k
. Here's a systematic way to approach this:
- Start by sorting the array
nums
. Sorting helps in efficiently finding pairs that satisfy the given condition by using a two-pointer technique. - Initialize two pointers, one (
left
) at the beginning of the array and the other (right
) at the last element. - Use a variable
max_sum
to keep track of the maximum sum encountered that is also less thank
. - Iterate over the array using the two pointers:
- Calculate the sum of elements at the
left
andright
pointers. - If this sum is less than
k
, compare it withmax_sum
and updatemax_sum
if this sum is greater. - If the sum is less than
k
, increase theleft
pointer to try and get a larger sum. - If the sum is equal to or greater than
k
, decrease theright
pointer to reduce the sum.
- Calculate the sum of elements at the
- Continue this process until the
left
pointer is not less than theright
pointer. - After completing the loop, check the value of
max_sum
. If it has changed from its initial value (suggesting a valid sum was found), return it. Otherwise, return-1
, indicating no valid pair was found.
By following this method, we efficiently search for the highest pair sum under the given constraints without needing to check all possible pairs, thus optimizing the process.
Solutions
- C++
- Java
- Python
class Solution {
public:
int pairSumLessThanK(vector<int>& arr, int limit) {
int bestSum = -1;
int frequency[1001] = {};
for (int v : arr) {
frequency[v]++;
}
int left = 1;
int right = 1000;
while (left <= right) {
if (left + right >= limit || frequency[right] == 0) {
right--;
} else {
if (frequency[left] > (left < right ? 0 : 1)) {
bestSum = max(bestSum, left + right);
}
left++;
}
}
return bestSum;
}
};
The solution for the "Two Sum Less Than K" problem in C++ involves finding the maximum sum of pairs in an array whose sum is less than a specified value K
(here indicated as limit
). The given approach uses a two-pointer technique combined with a frequency array to efficiently solve the problem.
- Begin by initializing the
bestSum
to-1
, to handle cases where no valid pair sum exists. - Create a frequency array of size 1001 (assuming the values range from 1 to 1000) to count occurrences of each integer in the input vector
arr
. - Populate the frequency array by iterating through each value in
arr
. - Use two pointers
left
andright
, initially set to 1 and 1000 respectively, to explore potential pairs. - Use a while loop to consider pairs from the smallest and largest possible values inward. Terminate if
left
is greater thanright
. - If the sum of
left
andright
is greater than or equal tolimit
or if there are no occurrences ofright
inarr
, decrementright
. - Otherwise, if the frequency of
left
is sufficient (considering ifleft
equalsright
, at least 2 occurrences are needed), updatebestSum
with the maximum ofbestSum
and the current sum ofleft
andright
. Then, incrementleft
. - Continue this process until all possible pairs have been considered.
- Return
bestSum
, which holds the maximum sum of any pair with a sum less thanlimit
found in the array.
This method is efficient as it avoids the naive O(n^2) complexity associated with checking all possible pairs directly, leveraging the counting sort principle and two-pointer strategy to locate the optimal pair.
class Solution {
public int maxSumUnderK(int[] elements, int threshold) {
int maxSum = -1;
int[] frequency = new int[1001];
for (int element : elements) {
frequency[element]++;
}
int low = 1;
int high = 1000;
while (low <= high) {
if (low + high >= threshold || frequency[high] == 0) {
high--;
} else {
if (frequency[low] > (low < high ? 0 : 1)) {
maxSum = Math.max(maxSum, low + high);
}
low++;
}
}
return maxSum;
}
}
The code snippet provided is a Java method named maxSumUnderK
designed to solve the problem of finding two distinct elements in an array whose sum is the maximum possible under a given threshold, threshold
.
Here's how it works:
- An auxiliary array,
frequency
, is used to track the occurrences of each element in the input arrayelements
. - The variable
maxSum
initializes at -1 and will store the maximum sum that is less thanthreshold
. - The approach uses a two-pointer technique with
low
starting at 1 (smallest possible element value) andhigh
at 1000 (largest possible for this logic), iterating and adjusting to find the element pairs. - The conditions inside the loop manage the
low
andhigh
pointers:- If
low + high
is not less thanthreshold
orfrequency[high]
is zero (i.e.,high
is not inelements
), decrementhigh
. - Otherwise, if
frequency[low]
is greater than a certain condition (accounts for distinct elements criteria in a slightly optimized manner), updatemaxSum
if the new pair sum is greater. - Then, increment
low
.
- If
- Finally, the method returns
maxSum
, which at the end of method execution would hold the highest sum of any pair of numbers from the array that is less thanthreshold
.
Important elements affecting the solution approach and optimizations include:
- Use of a frequency array for constant time access to determine the presence of a specific integer in the input (effective for bounded range of integers).
- Two-pointer technique, a common strategy for array problems, optimizing the search for valid pairs in linear time relative to the range of values.
- The conditions and updates within the loop ensure that only valid pairs (distinct and sum under
threshold
) are considered.
This algorithm is efficient for problems bound within a known range (1 to 1000 here) and leverages space-time tradeoffs (auxiliary space in exchange for faster checks) typical in competitive programming or constrained environments.
class Solution:
def sumPairsBelowK(self, numbers: List[int], limitK: int) -> int:
bestSum = -1
numCount = [0] * 1001
for number in numbers:
numCount[number] += 1
low = 1
high = 1000
while low <= high:
if low + high >= limitK or numCount[high] == 0:
high -= 1
else:
if numCount[low] > (0 if low != high else 1):
bestSum = max(bestSum, low + high)
low += 1
return bestSum
The provided Python program tackles the problem of finding the maximum summation of a pair of numbers from a given list, where the sum is less than a specified limit, ( K ). The solution employs a two-pointer technique to efficiently explore possible pairs within an array of numbers.
Below is an outline of the logic utilized in the solution:
Initial Setup:
- A
bestSum
variable is initialized to -1 to keep track of the highest sum found that is less than ( K ). - A list
numCount
of size 1001 is initialized to zero. This list is used to count occurrences of each number in the input listnumbers
.
- A
Counting Elements:
- Iterate through each number in the
numbers
list, updating thenumCount
list to reflect the frequency of each number.
- Iterate through each number in the
Finding Pairs:
- Two pointers,
low
starting at 1 andhigh
starting at 1000, are used to explore pairs. - The while loop continues as long as
low
is less than or equal tohigh
. - The condition inside the loop checks if the sum of
low
andhigh
is less than ( K ) and if the currenthigh
number is present in the list (checked usingnumCount[high]
). - If the sum is greater than or equal to ( K ) or if
high
is not in the list, decrementhigh
. - Otherwise, check if there are enough occurrences of
low
(taking care to handle the case wherelow
equalshigh
) to form a pair and potentially updatebestSum
. - If conditions are met, increment
low
.
- Two pointers,
Return Result:
- After exiting the loop,
bestSum
contains the maximum sum of pairs that is less than ( K ) or remains at -1 if no such pair exists.
- After exiting the loop,
This approach efficiently finds the desired sum without needing to evaluate every possible pair directly, leveraging the frequency count and two-pointer strategy for a more optimal solution.
No comments yet.