A
A
Abn302020-05-27 21:51:59
Algorithms
Abn30, 2020-05-27 21:51:59

How to write an algorithm that searches for a sum equal to a number from the elements of an array?

Help me write an algorithm that looks for a sum from the elements of the array, which will be equal to a certain number of elements in the array (0< but >=100)
for example:
Given an array of 6 elements and given the number 12
Array elements: 1 2 5 6 6 3 .
Here 6 + 6 = 12, 1+5+6=12.1+2+3+6=12, it is enough to output one of the sums (for example: 6 6)

Answer the question

In order to leave comments, you need to log in

3 answer(s)
D
dmshar, 2020-05-27
@dmshar

Task: How to find from a limited number of numbers those from which it is possible to compose an input number?

H
hint000, 2020-05-28
@hint000

Sort the array in descending order, then recursively iterate until the sum matches.
It is possible without sorting, but I'm afraid that on large array sizes without sorting, the speed of the algorithm will drop catastrophically (the condition for exiting the recursion will be "weaker" without sorting).

D
darst, 2020-06-04
@darst

Sort the array in ascending order. You take the 0 element and the extreme right. You add them up, if the sum is more than the desired number, then the right element decreases by one, if less, then the left element increases by one, and so on until you find the right one or meet.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question