A
A
Artem Kondratsky2019-11-18 15:31:05
Python
Artem Kondratsky, 2019-11-18 15:31:05

How to find the optimal amount?

Hello, help me understand. There is an array of numbers, you need to find two numbers whose sum does not exceed n.
Example:
arr = [5, 3, 8, 10]
n = 15
it's more logical to take 5 and 10
, it seems to be nothing complicated, but it turns out a lot of if and it's kind of like a crutch. How to do it not crutch and beautiful?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
I
Ivan Melnikov, 2019-11-18
@kondrackii

Using the two pointer method, you run through the entire array. As soon as you meet the desired pair of numbers, break the loop.
And if you need a pair with a maximum sum not exceeding n (which is most likely), then do not interrupt the loop.

D
Developer, 2019-11-18
@samodum

Lots of ifs are replaced by loops

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question