ProgrammingVery hardAmazon OA · Goldman Sachs OA
What will be the output of the following pseudocode?
What will be the output of the following pseudocode?
Integer coins[4] = {9, 6, 5, 1} // sorted largest first
Integer amt = 11, used = 0
for (each i from 0 to 3)
while (amt >= coins[i])
amt = amt - coins[i]
used = used + 1
end while
end for
Print used- A. 3
- B. 2
- C. 4
- D. 11
Correct answer: A. 3
The greedy method takes 9 and then 1 + 1: 3 coins. It is not optimal here: 6 + 5 makes 11 with only 2 coins. Greedy is safe for systems like 1, 2, 5, 10 but not for every set of coins.
Practise more Pseudocode and Code Tracing questionsPseudocode and Code Tracing: notes and key points
More Pseudocode and Code Tracing questions
- What will be the output of the following pseudocode? Integer a[8] = {10, 9, 2, 5, 3, 7, 101, 18} Integer L[8], best = 0 for (each i from 0…
- What will be the output of the following pseudocode? (strings are indexed from 0) String x = "SUNDAY", y = "SATURDAY" Integer…
- What will be the output of the following pseudocode? Integer a[6] = {5, 5, 10, 100, 10, 5} Integer incl = 0, excl = 0, t for (each i from…
- An array of n elements is ALREADY sorted in increasing order. What is the time complexity of this pseudocode on it? for (each i from 1 to…
- What is the time complexity of the following pseudocode, as a function of n? Procedure f(Integer n) if (n <= 1) return end if for (each i…
- What will be the output of the following pseudocode? (All variables are integers, so / is integer division) Integer n = 7086351, s = 0, d…