Files
leetcode/apps/docs/content/(05-decision-space)/greedy/index.mdx
T

94 lines
2.6 KiB
Plaintext

---
title: Greedy
description: 'The best local choice is made at each step and is not changed later.'
hidden: true
---
## When to use greedy algorithms?
- Solving optimization problems.
- Ask to optimize some value and calculate it.
- keywords (min/max, longest/shortest, largest/smallest, etc.)
## Optimization problems
1. Return the minimum number of swaps required to make s1 equal to s2.
2. Return the minimum number of steps to make s and t anagrams of each other.
3. Given three integers a, b, and c, return the longest possible happy string, if there are multiple such strings return any of them. if there is no such string, return empty string.
## What are greedy algorithms?
- Greedy algorithms follow this format:
- identify what choices you have at every step
- find the best choice
- just do what looks best until done
- assume that the best choice is the one that will lead to the best outcome
## How do we know greedy works?
- Write out a formal proof
- too complicated to write out
- too much time
- better to use intuition
- try a bunch of ideas
- find counterexamples
## Steps to use greedy algorithms
<Steps>
<Step title="Identify the different steps and choices">
- Choices have to be comparable
- must determine if a choice is better than another
</Step>
<Step title="Check if greedy works">
- try finding small cases where greedy is not optimal
- if cases pass, try to deduce why greedy is optimal
</Step>
</Steps>
## Why use greedy algorithms?
- simple to code
- doesn't use complex algorithms (BFS, DFS, etc.)
- runtime is fast, usually 0(n) or O(nlogn)
- however, greedy algorithms are not always optimal
## The Greedy Skeleton
### Type 1: Walk and Carry
:::info
No sort. Walk the list once. Carry one number. At each step, decide: keep it, or drop it.
:::
```python
def walk_and_carry(nums):
carry = start_value
best = start_value
for n in nums:
if carry_is_useless(carry):
carry = fresh_start
carry = update(carry, n)
best = max(best, carry)
return best
```
### Type 2: Sort and Pick
:::info
Used when order doesn't matter, so you pick the order. Meeting rooms, intervals, "most tasks by a deadline."
:::
```python
def greedy(items):
# 1. Sort by the greedy key (deadline, end time, size, ratio, ...)
items.sort(key=greedy_key)
result = 0
state = initial_state()
for item in items:
# 2. Take the item only if the locally best choice is valid
if is_feasible(item, state):
result += take(item, state)
# 3. Correctness relies on an exchange argument, not just passing tests
return result
```