Teaching Kids Programming – Sum of Two Numbers Less Than Target using Two Pointer Algorithm


Teaching Kids Programming: Videos on Data Structures and Algorithms

Given a list of integers nums and an integer target, return the sum of the largest pair of numbers in nums whose sum is less than target. You can assume that there is a solution.

Constraints
2 ≤ n ≤ 100,000 where n is the length of nums
Example 1
Input
nums = [5, 1, 2, 3]
target = 4
Output
3
Explanation
Sum of the largest pair of numbers less than 4 is 1 + 2 = 3.

Hints:
Two pointers (left& right) and keep maximizing the result

Bruteforce Algorithm to Get the Two Sum Maximum less than Target

Bruteforcing all possible pairs takes O(N^2) and we then can check the sum of each pair and record the maximum if it is less than target.

1
2
3
4
5
6
7
8
9
class Solution:
    def largestTwoSumLessThanTarget(self, nums, target):
        n = len(nums)
        ans = -math.inf
        for i in range(n):
            for j in range(i + 1, n):
                if nums[i] + nums[j] < target:
                    ans = max(ans, nums[i] + nums[j])
        return ans
class Solution:
    def largestTwoSumLessThanTarget(self, nums, target):
        n = len(nums)
        ans = -math.inf
        for i in range(n):
            for j in range(i + 1, n):
                if nums[i] + nums[j] < target:
                    ans = max(ans, nums[i] + nums[j])
        return ans

Two Pointer Algorithm to Get the Largest Two Sum less than Target

If we sort the array (which takes O(NLogN) by the way), we can apply two pointer in O(N) time. And move the corresponding pointer respectively.

1
2
3
4
5
6
7
8
9
10
11
12
13
class Solution:
    def largestTwoSumLessThanTarget(self, nums, target):
        nums.sort()
        i, j = 0, len(nums) - 1
        ans = -math.inf
        while i < j:
            x = nums[i] + nums[j]
            if x < target:
                ans = max(ans, x)
                i += 1
            else:
                j -= 1
        return ans
class Solution:
    def largestTwoSumLessThanTarget(self, nums, target):
        nums.sort()
        i, j = 0, len(nums) - 1
        ans = -math.inf
        while i < j:
            x = nums[i] + nums[j]
            if x < target:
                ans = max(ans, x)
                i += 1
            else:
                j -= 1
        return ans

The overall time complexity is O(NLogN) as sorting is dominant.

See also: Two Pointer Algorithm to Count the Sum of Three Numbers Less than Target

See also: Teaching Kids Programming – Lowest Sum of Pair Larger than Target via Two Pointer

Two Sum Variation Problems

–EOF (The Ultimate Computing & Technology Blog) —

GD Star Rating
loading...
484 words
Last Post: Convert UTF Encoding to UCS in PHP
Next Post: Javascript/NodeJS Function to Check the Plugins on Steem Blockchain RPC Nodes

The Permanent URL is: Teaching Kids Programming – Sum of Two Numbers Less Than Target using Two Pointer Algorithm

Leave a Reply