LeetCode 1099: Two Sum Less Than K Solution
Master LeetCode problem 1099 (Two Sum Less Than K), a easy challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
1099. Two Sum Less Than K
Problem Explanation
Explanation:
To solve this problem, we can use a two-pointer approach. We first sort the input array in ascending order. Then, we initialize two pointers left
and right
at the beginning and end of the sorted array respectively. We iterate through the array and move the pointers based on the sum of the elements pointed by them. If the sum is less than K
, we update the maximum sum found so far and move the left
pointer to the right. Otherwise, we move the right
pointer to the left. We continue this process until the two pointers meet or pass each other.
Finally, we return the maximum sum found which is less than K
, or -1 if no such sum exists.
Time Complexity:
The time complexity of this approach is O(n log n) due to the sorting step, where n is the number of elements in the input array.
Space Complexity:
The space complexity is O(1) as we only use a constant amount of extra space.
:
Solution Code
class Solution {
public int twoSumLessThanK(int[] nums, int K) {
Arrays.sort(nums);
int left = 0, right = nums.length - 1;
int maxSum = -1;
while (left < right) {
int sum = nums[left] + nums[right];
if (sum < K) {
maxSum = Math.max(maxSum, sum);
left++;
} else {
right--;
}
}
return maxSum;
}
}
Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 1099 (Two Sum Less Than K)?
This page provides optimized solutions for LeetCode problem 1099 (Two Sum Less Than K) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 1099 (Two Sum Less Than K)?
The time complexity for LeetCode 1099 (Two Sum Less Than K) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 1099 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 1099 in Java, C++, or Python.