Intro
An algorithmic paradigm that follows the problem solving approach of making the locally optimal choice at each stage with the hop of finding a global optimum.
Pros - simple, easy to implement, run fast
Cons - Very often they don’t cover all the cases
Greedy problems:
- Greedy: A global optimum can be arrived at by selecting a local optimum.
- Optimal Substructure: An optimal solution to the problem contains an optimal solution to the subproblems.
Problems
- Activity Selection Problem
- Huffman Coding
- Job Sequencing Problem
- Fractional Knapsack Problem
- Prim’s Minimum Spanning Tree
621. Task Scheduler
Video: https://www.youtube.com/watch?v=ySTQCRya6B0
[Solution]
- Maximum possible number of idle slots is defined by the frequency of the most frequent task
- Allocate the most frequent number first, maximum idle = (max_freq - 1) * n
- total time = amount of task + amount of idle
1 | def leastInterval(self, tasks: List[str], n: int) -> int: |
630. Course Schedule III
Leetcode: https://leetcode.com/problems/course-schedule-iii/
Solution: https://leetcode.com/problems/course-schedule-iii/solution/ Iterative solution is very greedy
1 | def scheduleCourse(self, courses: List[List[int]]) -> int: |
1054. Distant Barcodes
Leetcode: https://leetcode.com/problems/distant-barcodes/
Solution:
Use a max heap to allocate the max count values first.
1 | from heapq import * |
767. Reorganize String
Leetcode: https://leetcode.com/problems/reorganize-string/
Note:
Same as above, arrange characters with higher frequency first.
1 | from heapq import * |
406. Queue Reconstruction by Height
Leetcode: https://leetcode.com/problems/queue-reconstruction-by-height/
Solution: Since all the people only count the amount of people taller or equal to themselves, the shortest person is irrelavant to the other people in the group. So we can first arrange everybody else and then insert the shortest person into appropriate place. Since the shortest person counts all the taller/equal person in front of him, then the insertion position should be the counts of the shortest person.
1 | var reconstructQueue = function(people) { |
1 | def reconstructQueue(self, people): |
Note: In python we can sort with two keys with lambda
function. The use of list.insert(element, index)
method in python is similiar to splice()
in javascript.
45. Jump Game II
Leetcode: https://leetcode.com/problems/jump-game-ii/
Note:
- Always jump to a place that will take us the farthest
curEnd
is used to track the furthurest place we can go on the current step- Once we reach
curEnd
, we extend it tocurFur
, and count how many extensions have we made
1 | def jump(self, nums: List[int]) -> int: |
517. Super Washing Machines
Leetcode: https://leetcode.com/problems/super-washing-machines/
134. Gas Station
Leetcode: https://leetcode.com/problems/gas-station/
Video: https://www.youtube.com/watch?v=nTKdYm_5-ZY&list=PLupD_xFct8mETlGFlLVrwbLwcxczbgWRM&index=8&t=0s
[Solution]
- One pass: Use memoization to keep track of how much gas do we lack
1 | def canCompleteCircuit(self, gas: List[int], cost: List[int]) -> int: |
Peak and valley problem
738. Monotone Increasing Digits
Leetcode: https://leetcode.com/problems/monotone-increasing-digits/
- Find the first decreasing point
- Reduce the digit at the decreasing point by 1, and fill the rest with 9
1 | class Solution: |
1838. Frequency of the Most Frequent Element
- Note: use float to prevent super big sums
1 | def maxFrequency(self, nums: List[int], k: int) -> int: |
53. Maximum Subarray
Leetcode: https://leetcode.com/problems/maximum-subarray/
Greedy Solution:
Pick the locally optimal move at each step, and that will lead to the globally optimal solution
Current maximum window: If max[i - 1] > 0
: include [i - 1]
element. Else, set maximum to yourself.
1 | def maxSubArray(self, nums: List[int]) -> int: |
122. Best Time to Buy and Sell Stock II
Leetcode: https://leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/description/
Solution:
- Remember the lowest previous price before current day
- Move on to find the next valley
1 | class Solution: |