arrow_back How do I write an algorithm that looks for the sum equal to a number in an array?

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

1 comment

6 and 6 are two elements from the array.
What is the condition?
Need to output a certain number of elements for a given amount? (2 - for 6-k, from the example)

3 Answers

0 votes
Sort the array in ascending order. Take the 0th element and the rightmost one. Add them up, if the sum is greater than the desired number, then the right element decreases by one, if less, then the left one increases by one, and so on until you find the desired one or they meet.
0 votes
Sort the array in descending order, then recursively search until the sum matches.
You can do it without sorting, but I'm afraid that on large array sizes without sorting the speed of the algorithm will fall catastrophically (the recursion exit condition will be "weaker" without sorting).
0 votes


dmshar , thank you, I formulated my question, but I repeat that it is possible to deduce from any summands the required sum equal to a given number
Form the problem. How many sums do you need to find? By the way, in your example 12 gives both 1+5+6 and 1+2+3+6.
Yes, approximately, from a certain number of numbers, find the sum of the numbers, which will be equal to the entered number