ProgrammingVery hardCAT · MBA placement
Fractional knapsack with capacity 50. Items as (value, weight): (60,10), (100,20), (120,30). Items are sorted by value per unit weight, highest first, and the fraction of an item may be taken. What total value is printed (an integer)?
Fractional knapsack with capacity 50. Items as (value, weight): (60,10), (100,20), (120,30). Items are sorted by value per unit weight, highest first, and the fraction of an item may be taken. What total value is printed (an integer)?
cap = 50; total = 0
for each item (v, w) in ratio order
if w <= cap then total += v; cap -= w
else total += v * cap / w; cap = 0
end for
Print total- A. 240
- B. 220
- C. 160
- D. 280
Correct answer: A. 240
Taking the fraction 20/30 of the 120 item adds 80, giving 240. Whole items only give 160, the 0/1 optimum 220 forbids fractions, and summing all values ignores the capacity of 50.
Practise more Pseudocode and Code Tracing questionsPseudocode and Code Tracing: notes and key points
More Pseudocode and Code Tracing questions
- Gas stations on a circle: gas = [1,2,3,4,5], cost = [3,4,5,1,2]. Station i gives gas[i] and then costs cost[i] to leave for station i+1…
- Ropes are to be merged into one. Merging two ropes of lengths a and b costs a + b and yields one rope of length a + b. Ropes have lengths…
- Stock prices by day: 3, 8, 2, 9, 1, 6. One share may be bought once and sold once later (later day only). The procedure below runs. What…
- Currency notes are paid out greedily from the largest denomination down, using as many notes of each denomination as possible. For amount…
- A number is given as the digit string 1432219. Exactly 3 digits must be deleted (the digits keep their order) so that the remaining number…
- The same stack method is applied to the string 5317 with exactly 2 digits deleted, but now the aim is the LARGEST number. The procedure…