notes/OJ notes/pages/Leetcode Maxinum-subarray.md

99 lines
1.9 KiB
Markdown
Raw Normal View History

2022-06-14 23:33:35 +08:00
# Leetcode Maxinum-subarray
#### 2022-06-09
---
2022-09-03 15:41:36 +08:00
2022-06-14 23:33:35 +08:00
##### Data stuctures:
2022-09-03 15:41:36 +08:00
#DS #array
2022-06-14 23:33:35 +08:00
##### Algorithms:
2022-09-03 15:41:36 +08:00
2022-06-14 23:33:35 +08:00
#algorithm #Kadane_s_algorithm
2022-09-03 15:41:36 +08:00
2022-06-14 23:33:35 +08:00
##### Difficulty:
2022-09-03 15:41:36 +08:00
2022-06-14 23:33:35 +08:00
#leetcode #coding_problem #difficulty-easy
2022-09-03 15:41:36 +08:00
2022-06-14 23:33:35 +08:00
##### Links:
2022-09-03 15:41:36 +08:00
2022-06-14 23:33:35 +08:00
- [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)
2022-09-03 15:41:36 +08:00
2022-06-14 23:33:35 +08:00
##### Related topics:
2022-09-03 15:41:36 +08:00
2022-06-14 23:33:35 +08:00
### Problem
2022-09-03 15:41:36 +08:00
2022-06-14 23:33:35 +08:00
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
2022-09-03 15:41:36 +08:00
2022-06-14 23:33:35 +08:00
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;
2022-09-03 15:41:36 +08:00
2022-06-14 23:33:35 +08:00
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]);
2022-09-03 15:41:36 +08:00
2022-06-14 23:33:35 +08:00
if (local_max > global_max) {
// We take note when local_max achieves the peak.
global_max = local_max;
}
}
return global_max;
}
};
```
### Thoughts
2022-09-03 15:41:36 +08:00
This is a [[Kadane's Algorithm]] problem, and the philosophy behind it id divide and conquer.
2022-06-14 23:33:35 +08:00
local_max is the max accumulated number we've found, and global_max is the max local_max we've found.
2022-09-03 15:41:36 +08:00
2022-06-14 23:33:35 +08:00
```cpp
local_max = max(nums[i] + local_max, nums[i])
```
2022-09-03 15:41:36 +08:00
2022-06-14 23:33:35 +08:00
is the key to O(n) complexity.
> [!hint]
2022-09-03 15:41:36 +08:00
> Use the macro INT_MAX and INT_MIN to initialize variables that finds max / min var. #tip