3.7.5 · D3 · HinglishAlgorithm Paradigms

Worked examplesWhen greedy fails — 0 - 1 knapsack counter-example

4,303 words20 min read↑ Read in English

3.7.5 · D3 · Coding › Algorithm Paradigms › When greedy fails — 0 - 1 knapsack counter-example

Yeh page ek drill room hai. Parent note ne ek baar prove kar diya ki density-greedy fail hoti hai. Yahan hum har tarah ka instance cover karenge taaki koi bhi case aisa na ho jo tumne pehle dekha na ho.

Shuru karne se pehle, vocabulary ka ek reminder — koi bhi symbol use karne se pehle define kiya jayega.


Scenario matrix

Neeche har row ek case class hai — ek alag tarika jis mein greedy-vs-optimal ki kahaani ho sakti hai. Worked examples mein baad mein [Cell 3] jaisi tag hogi taaki tum dekh sako ki sab cover hua.

Cell Case class Kya stress karta hai Example
1 Greedy = OPT (lucky) greedy abhi bhi sahi ho sakti hai Ex 1
2 Greedy < OPT (classic gap) wasted capacity ek combo block karta hai Ex 2
3 Sort-by-value greedy fail wrong key capacity hog karti hai Ex 3
4 Degenerate: kuch fit nahi zero-item answer Ex 4
5 Degenerate: sab fit ho jaata capacity total weight Ex 5
6 Zero-value / zero-weight items edge inputs , Ex 6
7 Greedy arbitrarily bad tiny high-density item ruin kar deta hai Ex 7
8 ½-approximation rescue guaranteed sasta fix Ex 8
9 Real-world word problem translate → solve Ex 9
10 Exam twist: DP table banao hand se bharo Ex 10

Har example ka Forecast padho aur scroll karne se pehle guess karo. Woh guess hi point hai.


Figure — When greedy fails — 0 - 1 knapsack counter-example
Figure 1. Capacity line tak ek single stacked bar: A (orange, 10) + B (violet, 20) + C (magenta, 20) bag ko exactly tak fill karta hai bina kisi gap ke, total value .

  1. Densities. , , . Yeh step kyun? Greedy ka sirf input density ordering hai, toh pehle isse compute karo.
  2. Greedy walk. A lo (room , value ). B lo (room , value ). C try karo (needs , room exactly fits), value . Yeh step kyun? Greedy har item tab leta hai jab fit ho; yahan kuch skip nahi hota.
  3. Greedy total , room left . Yeh step kyun? Li gayi values sum karo aur confirm karo ki bag exactly full hai — zero waste warning sign hai ki greedy already optimal ho sakti hai.
  4. Kya kuch better hai? Teeno items ka total weight hai, toh sab items ek saath fit ho jaate hain. Sach mein "sab lo" se beat nahi kar sakte. Yeh step kyun? Jab poora set fit ho jaaye, OPT = sum of all values, koi search nahi chahiye.

Verify: Greedy , OPT . Equal ✓.


Figure — When greedy fails — 0 - 1 knapsack counter-example
Figure 2. Capacity line tak do stacked bars. Left (orange/violet) greedy A+B hai, pe top out karta hai, hatched empty GAP ke saath aur total value . Right (violet/magenta) B+C hai, saare fill karta hai total value ke saath. Left ka empty slot exactly woh room hai jo item C ko chahiye tha.

  1. Densities. , , . Order: A, B, C. Yeh step kyun? Greedy ki marching order establish karo.
  2. Greedy walk. A lo (room , val ). B lo (room , val ). C try karo (needs ) → skip. Yeh step kyun? C ko slice nahi kar sakte (0/1 rule), toh greedy 20 units waste ke saath ruk jaata hai.
  3. Greedy total . Yeh step kyun? Li gayi items A+B ki values sum karo greedy ka final score record karne ke liye OPT se compare karne se pehle.
  4. OPT dhundho. B+C try karo: weight ✓, value . Yeh step kyun? Step 2 mein waste hue 20 units hint hain ki ek lower-density item (C) bag better fill kar sakta tha. A ki jagah C lena us gap ko recover karta hai.

Verify: Greedy , OPT . Shortfall coins, yaani greedy of optimal hai (≈27% worse) ✓.


Figure — When greedy fails — 0 - 1 knapsack counter-example
Figure 3. tak do stacked bars. Left (magenta) value-greedy hai: ek giant item H poore fill karta hai lekin sirf worth hai. Right (violet/orange) P+Q hai, poore fill karta hai aur worth hai. Same fill, bahut zyada value — heavy item value hog tha.

  1. Value se sort karo (density nahi). Order: H, Q, P. Yeh step kyun? Hum tempting "maximize value → valuable cheezein pehle lo" heuristic test kar rahe hain.
  2. Value-greedy walk. H lo (weight , room , value ). Room → P skip, Q skip. Yeh step kyun? H heavy aur valuable hai; ise pakadna poora bag monopolize kar leta hai.
  3. Value-greedy total . Yeh step kyun? Sirf H liya gaya, toh akela uska value heuristic ka score hai — true optimum nikalne se pehle record karo.
  4. OPT dhundho. P+Q: weight ✓, value . Yeh step kyun? Do lighter items milke single heavy hog se zyada value dete hain.

Verify: value-greedy , OPT . ✓.


Figure — When greedy fails — 0 - 1 knapsack counter-example
Figure 4. Ek tiny capacity line pe teen item-weight bars (10, 20, 30) se kaafi neeche. Koi nahi pohuncha — sab line ke upar hain, toh loaded bar empty hai (value 0).

  1. Har item ko se check karo. , , . Har item bahut heavy hai. Yeh step kyun? "Take if it fits" test sabke liye fail hota hai — greedy walk kuch nahi leta.
  2. Greedy total , room left . Yeh step kyun? Empty subset hi ek legal solution hai.
  3. OPT. Koi bhi subset (sivaaye ke) ka weight nahi, toh OPT bhi. Yeh step kyun? Ek degenerate instance jahan greedy aur OPT trivially zero pe agree karte hain.

Verify: Greedy , OPT ✓.


  1. Total weight. . Yeh step kyun? Agar poora set fit ho, toh capacity constraint inactive hai.
  2. Greedy walk. A, B, C lo — har ek hamesha-shrinking-lekin-phir-bhi-ample room mein fit hota hai. Total . Yeh step kyun? Greedy ko kabhi skip nahi karna padta; sab grab kar leta hai.
  3. OPT (sab lo — ek item add karna kisi nonnegative-value total ko kabhi nahi ghatata). Yeh step kyun? Slack capacity ke saath, OPT = sum of all values.

Verify: Greedy , OPT ✓.


  1. Densities — zeros ke saath careful. . Z ke liye: , toh upar wali infinite-density convention se, Z ko priority label milta hai ("free value" ⇒ pehle sorts). N ke liye: (last sorts). Yeh step kyun? ka koi finite ratio nahi, toh pehle define ki gayi convention use karte hain — Z ko "hamesha pehle" tag milta hai; ek genuine ordering phir bhi exist karti hai: Z, A, N.
  2. Greedy walk (rule jaisa likha hai). Z lo (label , weight → room hi rehta, value ). A lo (room , value ). N try karo (weight fits, toh greedy leta hai), value , room . Yeh step kyun? Hum "take if it fits" literally follow karte hain — N liya jaata hai chahe useless ho, kyunki rule value kabhi inspect nahi karta.
  3. Greedy total (Z + A + N; N ne contribute kiya). Yeh step kyun? Li gayi values sum karo; useless N total ko unchanged chhod deta hai, jo exactly woh point hai jo demonstrate kiya ja raha hai.
  4. OPT. Z free positive value hai ⇒ hamesha in (). A ek aur sirf positive-value weighted item hai (). N contribute karta hai toh include ya exclude karne se score nahi badlega. OPT . Yeh step kyun? Yahan greedy = OPT waise bhi hai — zero-value item harmless tha kyunki kaafi room bacha tha. Ek tighter bag mein, blindly N lena woh room waste kar sakta tha joh ek positive item ko chahiye tha, isliye real solvers ek guard add karte hain "don't take items"; lekin woh guard base rule ke upar ek optimization hai, base rule khud nahi.

Verify: Greedy , OPT ✓.


Figure — When greedy fails — 0 - 1 knapsack counter-example
Figure 5. Capacity line pe. Greedy bar (orange) height 1 ka ek sliver dikhata hai (item T, value 2) ek vast hatched gap of 999 ke saath. Optimal bar (magenta) ek solid block hai jo poore 1000 fill karta hai (item M, value 1500). Sliver ne giant ko block kar diya.

  1. Densities. , . Order: T, M. Yeh step kyun? T per kilo best lagta hai.
  2. Greedy walk. T lo (room , value ). M try karo (needs ) → skip. Yeh step kyun? Tiny item ne room ka 1 unit chura liya, aur itna kaafi hai giant ko block karne ke liye.
  3. Greedy total . Yeh step kyun? Sirf T liya gaya, toh akela uska value greedy ka score hai — compare karne se pehle record karo.
  4. OPT. Bas M lo: weight ✓, value . Yeh step kyun? Tiny lure ko drop karne se giant fit ho jaata hai.

Verify: Greedy , OPT , ratio ✓.


  1. Density-greedy value (Ex 7 se) . Yeh step kyun? Do candidates mein se ek.
  2. Best single item that fits. T () aur M (, aur toh fit hai) dono candidates hain; best hai M . Yeh step kyun? Yeh second candidate exactly Ex-7 disaster se bachata hai — ek lone giant jise greedy ne skip kar diya.
  3. Heuristic answer . Yeh step kyun? Do candidates mein se better lo.

Verify: HEUR , OPT , aur ✓.


Figure — When greedy fails — 0 - 1 knapsack counter-example
Figure 6. kg pe capped drone payload bar. Naive dispatch laptop+monitor (orange/violet) kg pe load karta hai ek -kg empty gap ke saath, fees \16050$220$.

  1. Knapsack mein translate karo. ; items A=laptop, B=monitor, C=printer. Yeh step kyun? Word problems disguise mein knapsack hain: capacity = payload, value = fee, integrality = "parcel split nahi kar sakte".
  2. Density-greedy (ek naive dispatcher kya karta hai). A phir B = \1603020$ bacha). Yeh step kyun? Tempting-but-wrong shortcut dikhata hai.
  3. Optimal load. monitor + printer kg , fees \100 + $120 = $220$. Yeh step kyun? Payload exactly fill karta hai; story ka "split nahi kar sakte" woh 0/1 constraint hai jo DP zaruri banata hai.

Verify: naive , optimal ✓.


Figure — When greedy fails — 0 - 1 knapsack counter-example
Figure 7. Bhara hua DP grid. Rows hain (items unlocked, orange labels); columns hain (violet labels). Har cell rakhta hai. Bottom-right cell magenta se highlight hai; ek arrow "skip" link dikhata hai cell directly above se.

  1. Row 0 (koi item nahi). sabhi ke liye. Yeh step kyun? Base case: koi item nahi → koi value nahi. Har DP yahan se grow hoti hai.
  2. Row 1 (item ). ke liye: . ke liye: . Row1 . Yeh step kyun? Ek item worth 3 fit hota hai jab room ho; zyada room value add nahi karta.
  3. Row 2 (item ).
    • : → bahut heavy → Row1 copy → .
    • : .
    • : .
    • : . Row2 . Yeh step kyun? pe hum dono items 1 aur 2 lete hain ( kg, ).
  4. Row 3 (item ).
    • : → bahut heavy → Row2 copy → .
    • : .
    • : . Row3 . Yeh step kyun? pe, items 1+2 rakhna (value 7) item 3 akele lene (value 5) se beat karta hai.
  5. Answer , items 1+2 se achieve hota hai. Yeh step kyun? Bottom-right cell poore problem ka answer hai — koi early commitment nahi, har cell pe dono take/skip try kiye.

Verify: , aur sabhi subsets of weight pe brute force bhi agree karta hai ✓.


Recall Quick self-quiz over the matrix

Density-greedy 0/1 knapsack pe guaranteed correct kab hoti hai? ::: Jab sab items fit ho jaayein (, Cell 5) ya trivially koi fit na ho (Cell 4) — yaani jab capacity kabhi choice force na kare. Kya fixed greedy rule ek item jo fit ho use leta hai? ::: Haan — rule hai "take iff it fits" aur value kabhi inspect nahi karta; Ex 6 dikhata hai ki woh N leta hai aur simply kuch gain nahi karta. Ex 7 greedy score vs OPT? ::: vs — greedy ne ~0.13% capture kiya, koi guarantee nahi prove hoti. ½-approximation kaunse do candidates compare karta hai? ::: density-greedy ki value, aur woh single sabse valuable item jo fit ho. ka matlab kya hai? ::: Pehle items aur capacity ke sub-bag se maximum value; answer hai . Ex 10 mein DP table ka final answer? ::: (items 1 aur 2). Zero-weight positive-value item ko kaise handle karte hain? ::: Ise priority do (hamesha pehle, hamesha lo) — Cell 6.


Connections

  • Parent: When greedy fails — woh theory jin examples ko ye drill karte hain
  • Dynamic Programming — Ex 10 DP by hand hai
  • Fractional Knapsack — jahan greedy actually optimal hai (Ex 2 se contrast); Ex 8 mein upper-bound lemma ka source
  • Greedy Algorithms · Greedy-Choice Property · Exchange Argument — kyun wahan proof hold karta hai, yahan nahi
  • Approximation Algorithms — Ex 8 ka ½-guarantee
  • NP-hardness — kyun koi fast exact greedy key exist nahi karti
  • Optimal Substructure — woh property jise DP recurrence exploit karta hai