Fruit Jar Problem

You have 3 jars that are all mislabeled. One jar contains Apple, another contains Oranges and the third jar contains a mixture of both Apple and Oranges. You are allowed to pick as many fruits as you want from each jar to fix the labels on the jars. What is the minimum number of fruits that you have to pick and from which jars to correctly label them?

💡Strategies for Solving This Problem

Classic Knapsack Variant

This is usually the 0/1 knapsack problem disguised with fruits. Common in Amazon and Microsoft interviews. I got a similar problem at Amazon in 2024.

The Problem

You have a jar with capacity C and n types of fruit. Each fruit type has a value and weight. Maximize the total value you can fit in the jar.

Each fruit can be taken once (0/1 knapsack) or unlimited times (unbounded knapsack). Clarify which version!

Why It's Tricky

Greedy doesn't work. Sorting by value-to-weight ratio and taking items in order can miss the optimal solution.

Example:

  • Fruit A: value 60, weight 10 (ratio 6)
  • Fruit B: value 100, weight 20 (ratio 5)
  • Fruit C: value 120, weight 30 (ratio 4)
  • Capacity: 50

Greedy takes A and B (160 total). Optimal is B and C (220 total).

Dynamic Programming Solution

dp[i][w] = max value using first i items with weight limit w

For each item, we choose:

  • Don't take it: dp[i-1][w]
  • Take it: value[i] + dp[i-1][w - weight[i]]

Take the maximum of these two.

Space Optimization

We only need the previous row of the DP table, so we can use 1D array instead of 2D. But need to iterate backwards to avoid overwriting values we still need.

At Amazon

My problem was about filling a delivery truck with packages. Same structure as knapsack. Started with 2D DP, interviewer asked me to optimize space to O(capacity).

Also asked: "What if items can be taken multiple times?" That's unbounded knapsack - slightly different recurrence.

Scroll to Top