99 lines
1.9 KiB
Markdown
99 lines
1.9 KiB
Markdown
# Leetcode Maxinum-subarray
|
|
|
|
#### 2022-06-09
|
|
|
|
---
|
|
|
|
##### Data stuctures:
|
|
|
|
#DS #array
|
|
|
|
##### Algorithms:
|
|
|
|
#algorithm #Kadane_s_algorithm
|
|
|
|
##### Difficulty:
|
|
|
|
#leetcode #coding_problem #difficulty-easy
|
|
|
|
##### Links:
|
|
|
|
- [Link to problem](https://leetcode.com/problems/maximum-subarray/)
|
|
- [Analysis](https://medium.com/@rsinghal757/kadanes-algorithm-dynamic-programming-how-and-why-does-it-work-3fd8849ed73d)
|
|
|
|
##### Related topics:
|
|
|
|
### Problem
|
|
|
|
Given an integer array `nums`, find the contiguous subarray (containing at least one number) which has the largest sum and return _its sum_.
|
|
|
|
A **subarray** is a **contiguous** part of an array.
|
|
|
|
#### Examples
|
|
|
|
Example 1:
|
|
|
|
```
|
|
Input: nums = [-2,1,-3,4,-1,2,1,-5,4]
|
|
Output: 6
|
|
Explanation: [4,-1,2,1] has the largest sum = 6.
|
|
```
|
|
|
|
Example 2:
|
|
|
|
```
|
|
Input: nums = [1]
|
|
Output: 1
|
|
```
|
|
|
|
Example 3:
|
|
|
|
```
|
|
Input: nums = [5,4,-1,7,8]
|
|
Output: 23
|
|
```
|
|
|
|
#### Constraints
|
|
|
|
- 1 <= nums.length <= 105
|
|
- -104 <= nums[i] <= 104
|
|
|
|
### Solution
|
|
|
|
```cpp
|
|
class Solution {
|
|
public:
|
|
int maxSubArray(vector<int>& nums) {
|
|
// Kadane's algorithm
|
|
int local_max = 0;
|
|
int global_max = INT_MIN;
|
|
|
|
for (int i = 0; i < nums.size(); i++) {
|
|
// if accumulated local max is smaller than nums,
|
|
// we use the new one instead, and it must be the biggest.
|
|
local_max = max(nums[i] + local_max, nums[i]);
|
|
|
|
if (local_max > global_max) {
|
|
// We take note when local_max achieves the peak.
|
|
global_max = local_max;
|
|
}
|
|
}
|
|
return global_max;
|
|
}
|
|
};
|
|
```
|
|
|
|
### Thoughts
|
|
|
|
This is a [[Kadane's Algorithm]] problem, and the philosophy behind it id divide and conquer.
|
|
local_max is the max accumulated number we've found, and global_max is the max local_max we've found.
|
|
|
|
```cpp
|
|
local_max = max(nums[i] + local_max, nums[i])
|
|
```
|
|
|
|
is the key to O(n) complexity.
|
|
|
|
> [!hint]
|
|
> Use the macro INT_MAX and INT_MIN to initialize variables that finds max / min var. #tip
|