Complete the code to calculate the value-to-weight ratio for each item.
double ratio = items[i].value [1] items[i].weight;The value-to-weight ratio is calculated by dividing the value by the weight.
Complete the code to sort items by their value-to-weight ratio in descending order.
sort(items.begin(), items.end(), [](const Item &a, const Item &b) { return a.ratio [1] b.ratio; });To sort in descending order, use '>' to compare ratios.
Fix the error in the loop condition to process items until capacity is full or all items are considered.
for (int i = 0; i [1] n && capacity > 0; i++) {
The loop should run while i is less than n to avoid out-of-bounds errors.
Fill both blanks to correctly update total value and capacity after taking a fraction of an item.
totalValue += items[i].ratio * [1]; capacity -= [2];
We add ratio * capacity (value for the fraction taken using remaining capacity) and reduce capacity by capacity (equivalent to setting it to 0).
Fill all three blanks to correctly take the whole item if it fits in capacity.
if (items[i].weight <= capacity) { totalValue += items[i].[1]; capacity -= items[i].[2]; } else { totalValue += items[i].ratio * [3]; capacity = 0; }
If the whole item fits, add its full value and reduce capacity by its weight. Otherwise, add fraction value for remaining capacity.
