I know you got the solution šŸ˜ Want to check?

Hi, welcome back!

You made it this far, keep up the great work!

Editorial for the problem: 1099. Two Sum Less Than K

Return the maximum sum of distinct pairs in the array such that the sum is less than k. If no such pair exists, return -1.

Before you read this email, make sure you’ve tried the solution on your own.

What would the time complexity of using a two-pointer solution be?

What would the time complexity of using two-pointers be?

Remember the array is not sorted

Login or Subscribe to participate in polls.

The key to being able to use this technique is to…. sort the array!

The first step we take is to sort the array! Sorting an array of N elements using a standard sorting algorithm (like the one used in Python's sorted function) has a time complexity of O(N log N).

Initialize two pointers:

L = 0

R = Array.size() - 1

maxSum=-1 (In case we don’t find any pairs)

The left pointer can only move to the right, and the right pointer can only move to the left.

At each step of the algorithm, we calculate the sum of array[L] + array[R].

If the sum is less than 'k', update the maximum sum and move the 'left' pointer to the right to explore larger sums.

If the sum is greater than or equal to 'k', move the 'right' pointer to the left to decrease the sum.

Let’s dig in with an example…

Day 4 Example

Solution:

Day 4 Solution

Let’s now add it to our LeetCode Tracker…

Leetcode Summary Table
Leetcode #SummaryNaive SolutionOptimizationBig O Notation
1099Two Sum Less Than KUse two nested for loops to find pairs whose sum is less than k.Sort the array and use two pointers to find the maximum sum of distinct pairs less than k.Naive Solution:
Memory: O(1)
Time Complexity: O(N^2)
Optimization:
Memory: O(1)
Time Complexity: O(N log N)

Enjoy your weekend and see you next Monday with a new challenge!

Denisse

Reply

or to participate.