Greedy algorithm [leetcode]

Notes: Random Thoughts on Code

overview

The essence of greed is to select the local optimum at each stage, so as to achieve the global optimum.

(1) Manual simulation by yourself. If the simulation is feasible, you can try the greedy strategy. If it is not feasible, you may need dynamic programming.

(2) The best strategy is to give a counterexample. If you can’t think of a counterexample, then try being greedy .

The four steps of chicken ribs

The greedy algorithm is generally divided into the following four steps:

  • Divide the problem into several sub-problems
  • Find a suitable greedy strategy
  • Find the optimal solution for each subproblem
  • Stack local optimal solutions into global optimal solutions

Leek

1. Handing out cookies

The local optimum here is to feed big biscuits to those with big appetites, and make full use of the biscuit size to feed one. The global optimum is to feed as many children as possible.

2. Swing sequence (upper lip)

Greedy: Greedy the places that are not the peak value.

3. Maximum subsequence sum

If -2 1 is together, when calculating the starting point, it must be calculated from 1, because negative numbers will only lower the sum, this is where greed is!

4. The best time to buy and sell stocks II

5. Jumping Game

6. Jumping Game II

7. The array sum maximized after k inversions

8. Gas station

The for loop is suitable for simulating traversal from beginning to end, while the while loop is suitable for simulating circular traversal, so be good at using while.

9. Hand out candy

10. Lemonade Change

11. Rebuild the queue based on height.

By analogy with 9, when encountering a trade-off between two dimensions, first determine one dimension, and then determine the other dimension.

Overlap interval

12. Detonate the balloon with the fewest number of arrows

13. No overlapping intervals

14. Divide letter intervals

15. Combine intervals

16. Monotonically increasing numbers

17. Monitor binary tree

Guess you like

Origin blog.csdn.net/qq_41804812/article/details/130174537