মূল কনটেন্টে যান
🌍
গ্লোবাল DSA
প্যাটার্নটপিক 10 · Greedy, Trie & Design

10.1 Greedy

চিনবেন কীভাবে
"minimize/maximize" where you can argue local best = global best — activity selection, scheduling, "pick the largest that fits". When unsure, compare with DP: if greedy is wrong, a counterexample exists (coin change breaks greedy → 9.3)
Demo · approach · কোড — আগে নিজে চেষ্টা, আটকালে খুলুন

Demo: CandyLC 135 (Hard — Google/Amazon High)

Statement (Demo): Children stand in a line with ratings. Give candies so that (1) every child gets at least one, and (2) a child with a higher rating than a neighbour gets more candies than that neighbour. Return the minimum total. Example: ratings=[1,0,2]5 (2, 1, 2) | ⚡ n ≤ 2×10⁴

Approach: Two passes — left→right: if the rating rises, give one more than the previous child; right→left: if the rating rises from the right, take the max to fix it. Both neighbour constraints are then satisfied.

function candy(ratings) {
  const n = ratings.length;
  const candies = new Array(n).fill(1);
  for (let i = 1; i < n; i++)
    if (ratings[i] > ratings[i - 1]) candies[i] = candies[i - 1] + 1;
  for (let i = n - 2; i >= 0; i--)
    if (ratings[i] > ratings[i + 1])
      candies[i] = Math.max(candies[i], candies[i + 1] + 1);
  return candies.reduce((a, b) => a + b, 0);
}

Complexity: Time O(n), Space O(n)

নোট · ফাঁকা

প্রবলেম

  • Activity SelectionGfG
    (sort by end time — the original greedy problem)

    Statement: Given the start and end times of n activities, return the maximum number one person can do if they cannot do two at once.
    Example: start=[1,3,0,5,8,5], end=[2,4,6,7,9,9]4 | ⚡ n ≤ 10⁵

    নোট · ফাঁকা
আরও দেখুন
Non-overlapping Intervals (greedy form) → primary 1.5; Task Scheduler and Refueling Stops (greedy + heap) → primary 6.4