Programmazione competitivaFacile

0-1 Zaino

Guida dettagliata e implementazione Python per il problema '0-1 Zaino'.

Dichiarazione del problema

Facile

Scrivi una funzione knapsack(W, wt, val, n) che trovi il valore massimo che può essere messo in uno zaino di capacità W utilizzando oggetti con pesi wt e valori val. Non è possibile dividere gli elementi; o prendi un oggetto o lo lasci.

Vincoli
  • 1 <= n <= 100
  • 1 <= W <= 1000
  • 1 <= wt[i], val[i] <= 1000

Esempi

Example 1
Input
knapsack(50, [10, 20, 30], [60, 100, 120], 3)
Output
220
Explanation

By taking items with weight 20 and 30, the total weight is 50, and the value is 100 + 120 = 220.

Example 2
Input
knapsack(10, [5, 4, 6, 3], [10, 40, 30, 50], 4)
Output
90
Explanation

By taking items of weight 4 and 3, the total weight is 7, and the value is 40 + 50 = 90.

Need a Hint?
Prendi in considerazione l'utilizzo di strutture dati specifiche della programmazione dinamica come set o heap.
Edge Cases to Watch
  • Strutture di input vuote
  • Ingressi a elemento singolo
  • Grandi limiti numerici

Pronto a risolvere?

Open the problem in PyRun's browser-based Python editor. Your code runs fully offline — no server required.

Apri nell'editor
Found this breakdown helpful?

PyRun is built and maintained by an independent solo developer. If this helped your interview prep, consider buying a coffee!

Buy me a coffee

Risorse Python consigliate

Espandi le tue conoscenze con tutorial interattivi, foglietti illustrativi e confronti di codici correlati.