notes/OJ notes/pages/Kadane's Algorithm.md

46 lines
1.4 KiB
Markdown
Raw Normal View History

2022-06-14 23:33:35 +08:00
# Kadane's Algorithm
#### 2022-06-09
---
2022-09-03 15:41:36 +08:00
2022-06-14 23:33:35 +08:00
##### Data structures:
2022-09-03 15:41:36 +08:00
2022-06-14 23:33:35 +08:00
#array
2022-09-03 15:41:36 +08:00
2022-06-14 23:33:35 +08:00
##### Algorithms:
2022-09-03 15:41:36 +08:00
#algorithm #Kadane_s_algorithm
2022-06-14 23:33:35 +08:00
##### Difficulty:
2022-09-03 15:41:36 +08:00
2022-09-06 20:22:48 +08:00
#CS_analysis #difficulty_easy
2022-09-03 15:41:36 +08:00
2022-06-14 23:33:35 +08:00
##### Time complexity:
2022-09-03 15:41:36 +08:00
2022-06-14 23:33:35 +08:00
O(n)
2022-09-03 15:41:36 +08:00
2022-06-14 23:33:35 +08:00
##### Related problems:
2022-09-03 15:41:36 +08:00
2022-06-14 23:33:35 +08:00
##### Resources:
2022-09-03 15:41:36 +08:00
2022-06-14 23:33:35 +08:00
- [Explainer article](https://medium.com/@rsinghal757/kadanes-algorithm-dynamic-programming-how-and-why-does-it-work-3fd8849ed73d)
---
2022-09-03 15:41:36 +08:00
2022-06-14 23:33:35 +08:00
### 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:
2022-09-03 15:41:36 +08:00
2022-06-14 23:33:35 +08:00
- You want to find the value of the highest peak or lowest valley
- The direction you search is mono-directional
2022-09-03 15:41:36 +08:00
- The current value can be obtained from or, is related to the value before this one.