notes/CS notes/pages/Kadane's Algorithm.md
2022-06-27 11:19:17 +08:00

42 lines
1.6 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# Kadane's Algorithm
#### 2022-06-09
---
##### Data structures:
#array
##### Algorithms:
#algorithm #Kadane_s_algorithm
##### Difficulty:
#CS_analysis #difficulty-easy
##### Time complexity:
O(n)
##### Related problems:
```expander
tag:#coding_problem tag:#Kadane_s_algorithm -tag:#template_remove_me
```
- [[Leetcode Best-Time-To-Buy-And-Sell-Stock]]
- [[Leetcode Maximum-Difference-Between-Increasing-Elements]]
- [[Leetcode Maxinum-subarray]]
##### Resources:
- [Explainer article](https://medium.com/@rsinghal757/kadanes-algorithm-dynamic-programming-how-and-why-does-it-work-3fd8849ed73d)
---
### What is Kadane's Algorithm?
It's a kind of dynamic programming. You calculate A[n] by calculating A[n - 1], which makes it O(n)
==local_maximum at index i is the maximum of (A[i] and the sum of A[i] and local_maximum at index i-1).==
> Because of the way this algorithm uses optimal substructures (the maximum subarray ending at each position is calculated in a simple way from a related but smaller and overlapping subproblem: the maximum subarray ending at the previous position) this algorithm can be viewed as a simple example of dynamic programming. Kadanes algorithm is able to find the maximum sum of a contiguous subarray in an array with a runtime of **_O(n)_**.
### When to use it?
According my analyze [[Leetcode Best-Time-To-Buy-And-Sell-Stock#Thoughts| here]], we should use it when these conditions are met:
- You want to find the value of the highest peak or lowest valley
- The direction you search is mono-directional
- The current value can be obtained from or, is related to the value before this one.