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

95 lines
2.1 KiB
Markdown
Raw Normal View History

2022-06-14 23:33:35 +08:00
# 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:
```expander
tag:#Kadane_s_algorithm
```
- [[Kadane's Algorithm]]
- [[Leetcode Best-Time-To-Buy-And-Sell-Stock]]
2022-07-10 08:29:59 +08:00
- [[Leetcode Maximum-Difference-Between-Increasing-Elements]]
2022-06-14 23:33:35 +08:00
### 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
2022-07-07 21:24:34 +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.
```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