Theoretical Basics of Greedy Algorithms
By choosing the local optimum at every stage, we aim to achieve the global optimum. The key to selecting a greedy algorithm is: it’s possible to deduce the global optimum from the local optimum.
How to verify if you can use greedy:
- Provide a counterexample: If you can’t think of a counterexample, try harder.
- Mathematical induction.
Steps for a greedy algorithm:
- Decompose the problem into several sub-problems.
- Identify an appropriate greedy strategy.
- Find the optimal solution for each sub-problem.
- Stack the local optimums to form a global optimum.
Example: Leetcode 455: Distributing Cookies
Local Optimum: Give the largest cookie to the child with the biggest appetite.
Global Optimum: Feed as many children as possible.
1 | class Solution: |
Example: Leetcode 376 Swing Sequence
This question is divided into three situations:
- there are flat slopes in the upper and lower slopes;
- only the first and last elements;
- monotonic slopes in which there are flat slopes; (prediff just records the direction of the initial slope when the swing appears)
Assume that the rightmost side has a slope, so the initial RESULT = 1.1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19class Solution:
def wiggleMaxLength(self, nums):
# only one element
if len(nums) == 1:
return 1
# three conditions: Up and down with flat slopes; first element; monotone with flat slopes
result = 1
prediff = 0 # This is equivalent to adding another element at the beginning of the array with the same value as its first element.
curdiff = 0
for i in range(len(nums) - 1):
curdiff = nums[i + 1] - nums[i]
if (prediff <= 0 and curdiff > 0) or (prediff >= 0 and curdiff < 0):
result += 1 # Satisfies the need for a flat slope up and down
# Dealing with monotony with flat slopes
prediff = curdiff
return resultExample: Leetcode 53 Maximum Subarray Sum
If successive sums are negative, they are immediately discarded and the next number is chosen as the starting position,using greedy algorithm:1
2
3
4
5
6
7
8
9
10
11
12
13
14
15class Solution:
def maxSubArray(self, nums):
result = -1000000 # Set result to a very small value
count = 0 # Record the current traversed value
for i in range(len(nums)):
count += nums[i]
if count > result:
result = count
if count < 0:
count = 0 # Reset count to start accumulating from the next position, reflecting the greedy approach
return result
Example: Leetcode 860 Lemonade To Find Change
Greedy thought: leave as many 5’s as possible because 5’s are more versatile and can make change not only to 20 but also to 10, whereas 10 can only make change to 20.
1 | class Solution: |
Theoretical Basics of Greedy Algorithms
1.Merge Intervals
2.Why Does MySQL Use B+ Trees Instead of Skip Lists for Indexing?
3.RESTful API
4.Database View
5.Database Indexing
6.MoreCAP
7.System Design
8.System Design

