-3

There is an array of n elements where any element is a natural number. To find a sum if present in the array without duplication while adding

Approach

  1. Remove all elements greater than the sum
  2. Sort the array in descending order
  3. Setting currentsum to 0
  4. Loop i where i = first element of array through last
  5. If currentsum + i <= sum then currentsum += i
  6. If currentsum == sum then print true
  7. Else print false

Is there any issues in this approach or is there test case that can give wrong answers.

clemens
  • 16,716
  • 11
  • 50
  • 65

1 Answers1

1

The algorithm presented in the question does not alyways yield the correct result. Consider an instance consisting of the values

7, 5, 3

which are already sorted in a decreasing manner. Let

8

be the target value for the sum. The algorithm in the question would select 7 as it is not larger that 8, however adding 5 and 3 is not possible as the target value 8 would be exceeded. Finally, the algorithm would output false. On the other hand, selection of 5 and 3 would yield a sum value of 8, which means that the output of the algorithm is wrong.

Codor
  • 17,447
  • 9
  • 29
  • 56