ProgrammingHardInfosys · Cognizant

Array a = [4, -2, 5, -1, 3]. Exactly k = 2 negations are applied: each one chooses the currently smallest element and replaces it by its negation (ties: first occurrence). What is printed as the final sum?

Array a = [4, -2, 5, -1, 3]. Exactly k = 2 negations are applied: each one chooses the currently smallest element and replaces it by its negation (ties: first occurrence). What is printed as the final sum?
repeat k times
    find the first index of the smallest element; negate it
end repeat
Print sum of a
  1. A. 13
  2. B. 15
  3. C. 5
  4. D. 9

Correct answer: B. 15

Negating -2 gives 2, then the smallest element is -1, which becomes 1, so the sum is 4+2+5+1+3 = 15. Applying only one negation gives 13, negating the first k elements gives 5, and skipping the negations gives 9.

More Pseudocode and Code Tracing questions

Exams that ask this topic