<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Harshita bansal on Medium]]></title>
        <description><![CDATA[Stories by Harshita bansal on Medium]]></description>
        <link>https://medium.com/@harshitabansal3737?source=rss-62b6336d06c6------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*SyHqWVn4E5dTjBa4t3d96w.jpeg</url>
            <title>Stories by Harshita bansal on Medium</title>
            <link>https://medium.com/@harshitabansal3737?source=rss-62b6336d06c6------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 17:20:14 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@harshitabansal3737/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[The Greedy Bet — When Greed Works and When It Fails]]></title>
            <link>https://medium.com/@harshitabansal3737/the-greedy-bet-when-greed-works-and-when-it-fails-821aa239b56b?source=rss-62b6336d06c6------2</link>
            <guid isPermaLink="false">https://medium.com/p/821aa239b56b</guid>
            <category><![CDATA[dynamic-programming]]></category>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[data-structure-algorithm]]></category>
            <category><![CDATA[competitive-programming]]></category>
            <category><![CDATA[greedy-algorithms]]></category>
            <dc:creator><![CDATA[Harshita bansal]]></dc:creator>
            <pubDate>Tue, 06 Jan 2026 15:58:53 GMT</pubDate>
            <atom:updated>2026-01-06T19:35:58.123Z</atom:updated>
            <content:encoded><![CDATA[<h3>The Greedy Bet — When it Works and When It Fails</h3><p>Have you ever stood in front of a pizza box with slices of different sizes and immediately gone for the biggest one? Or at an all-you-can-eat buffet, filled your plate with your favorite dish first? If so, you’ve already used a greedy algorithm in your daily life.</p><p>In computer science, a greedy algorithm is a problem-solving approach that makes the locally optimal choice at each step, hoping that these choices lead to a globally optimal solution. It’s intuitive, fast, and often effective - but not always. Let’s explore when greed works, when it backfires, and how to tell the difference.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/752/1*TwBj-SCF83frMHD4KovCKg.png" /></figure><h3>The Pizza Principle: A Delicious Introduction</h3><p>Imagine you’re sharing a pizza with friends, and the slices are uneven. Your goal? Maximize the amount of pizza you get. The constraint? You can only take one slice at a time. The local choice? Always pick the largest slice remaining. Backtracking? Not needed, you eat as you go.</p><blockquote>Simply put, A greedy algorithm makes the locally optimal choice at each step, trusting that these choices will lead to a globally optimal solution.</blockquote><p>The same logic applies at a buffet: if you want the most enjoyable meal, you start with your favorite dishes first (before they run out!).<br>But life and computer science aren’t always as simple as pizza or buffets.</p><h3>The Coin Change Problem</h3><p>Consider the coin change problem with coin denominations <strong>{1, 3, 4}</strong> and a target sum of <strong>6</strong>.</p><p>A greedy strategy would pick the largest coin possible at each step:</p><ul><li>Pick 4 → remaining sum = 2</li><li>Pick 1 → remaining sum = 1</li><li>Pick 1 → remaining sum = 0</li></ul><p>This results in the solution <strong>{4, 1, 1}</strong>, using <strong>3 coins</strong>.</p><p>But there is a better solution: <strong>{3, 3}</strong>, which uses only <strong>2 coins</strong>.</p><p>This example clearly shows that <strong>greedy does not always guarantee an optimal solution</strong>. Even though each step looked locally optimal, the final answer was not globally optimal.</p><p>Similar failures of greedy reasoning can appear in real-life scenarios like <strong>stock analysis</strong> or <strong>job offer selection</strong>, where choosing the best immediate option might block a better long-term outcome.</p><h3>The Knapsack Problem</h3><p>The knapsack problem beautifully illustrates both the strengths and limitations of greedy algorithms. Imagine you have a bag with a weight capacity and several items, each with a weight and a monetary value. Your goal is to maximize the total value without exceeding the capacity.</p><p>There are two main variants:</p><ol><li><strong>Fractional Knapsack</strong> : You can take fractions of items.</li><li><strong>0/1 Knapsack</strong> : You must either take an item entirely or leave it.</li></ol><h3><strong>Fractional Knapsack</strong></h3><p>Imagine you’re filling a delivery truck with a 50‑unit weight limit, and you can load partial shipments. A greedy thinker’s instinct kicks in: always load the most profitable cargo per unit weight first. In other words, prioritize shipments by value‑per‑weight, so every pound you carry maximizes your earnings.</p><p>You examine your shipments as shown in Fig. 1 below:</p><figure><img alt="Fractional Knapsack" src="https://cdn-images-1.medium.com/max/891/1*RWLnaA4qMW7rrNjVyVBJCA.png" /><figcaption>Fig. 1</figcaption></figure><p>Shipment A provides the highest value per unit weight, so you load it completely. The truck now has 40 units of space left.</p><p>Next, Shipment B looks optimal, so it goes in entirely. Now only 20 units remain. Shipment C weighs 30, but you don’t need the full shipment so you load <strong>two-thirds</strong> of it to fill the remaining space exactly.</p><p>By the time the truck is full, the total value loaded is <strong>240</strong>.</p><p>This simple greedy approach works perfectly here because fractions are allowed.</p><p><strong>Implementation (C++) :</strong></p><pre>#include &lt;bits/stdc++.h&gt;<br>using namespace std;<br><br><br>bool cmp(const pair&lt;double, pair&lt;double, int&gt;&gt; &amp;a,<br>         const pair&lt;double, pair&lt;double, int&gt;&gt; &amp;b)<br>{<br>    return a.first &gt; b.first;<br>}<br><br>int main() <br>{<br>    int n;<br>    cin &gt;&gt; n;<br><br>    double capacity;<br>    cin &gt;&gt; capacity;<br><br>    vector&lt;pair&lt;double, pair&lt;double, int&gt;&gt;&gt; v(n);<br><br>    for (int i = 0; i &lt; n; i++)<br>    {<br>        int profit, w;<br>        cin &gt;&gt; profit &gt;&gt; w;<br><br>        v[i].second.first = profit;<br>        v[i].second.second = w;<br>        v[i].first = (double)profit / w;<br>    }<br><br>    sort(v.begin(), v.end(), cmp);<br><br>    double maxProfit = 0.0;<br><br>    for (int i = 0; i &lt; n; i++)<br>    {<br>        if (capacity &lt;= 0)<br>            break;<br><br>        double profit = v[i].second.first;<br>        int w = v[i].second.second;<br><br>        if (w &gt; capacity)<br>        {<br>            maxProfit += profit * (capacity / w);<br>            capacity = 0;<br>        }<br>        else<br>        {<br>            maxProfit += profit;<br>            capacity -= w;<br>        }<br>    }<br><br>    cout &lt;&lt; maxProfit &lt;&lt; endl;<br>    return 0;<br>}</pre><p>Key Implementation Insights:</p><ol><li>Use double for ratios : Avoid integer division truncation: (double)profit / weight.</li><li>Sort descending by ratio : Greedy picks highest value/weight first.</li><li>Break when capacity ≤ 0 : Stop early if bag is full.</li><li>Full vs. fractional logic: Take whole item if fits, else fraction: profit × (capacity / w).</li><li>Keep data linked using nested pair: (ratio, (profit, weight)).</li><li>Capacity as double – Essential for fractional subtraction.</li></ol><h3><strong>0/1 Knapsack</strong></h3><p>Now, let’s consider the constraint where shipments <strong>must be loaded completely or not at all</strong>.</p><p>Following the same greedy strategy: take Shipment A first, then Shipment B. Now the truck holds 30 units, leaving no room for Shipment C. The total value is <strong>160</strong>.</p><p>However, if you look at all possibilities, there’s a better combination: skip Shipment A, take Shipments B and C instead. This yields a total value of <strong>220</strong>, <strong>higher than the greedy choice</strong>.</p><p>Here’s the key insight: when you cannot partially load items, the greedy approach can lead to suboptimal results.</p><blockquote>Early choices can block access to combinations that would maximize total value.</blockquote><p>You would require <strong>dynamic programming</strong> here!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=821aa239b56b" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>