notes/CS notes/pages/Leetcode Maxinum-subarray.md
2022-06-14 23:34:11 +08:00

2 KiB

Leetcode Maxinum-subarray

2022-06-09


Data stuctures:

#DS #array

Algorithms:

#algorithm #Kadane_s_algorithm

Difficulty:

#leetcode #coding_problem #difficulty-easy

tag:#Kadane_s_algorithm 

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

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.

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