Link

Easy DP Array

Adobe

Amazon

Apple

Bloomberg

Cisco

Expedia

Facebook

Google

JPMorgan

LinkedIn

Microsoft

Oracle

Salesforce

Uber

2020-05-15

53. Maximum Subarray

Similar Question: LeetCode Question 918

Question:

Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum.

Example:

Input: [-2,1,-3,4,-1,2,1,-5,4],
Output: 6
Explanation: [4,-1,2,1] has the largest sum = 6.

Solution:

No trick. Just use using Kadane’s algorithm.
Time: O(N)
Space: O(1)

class Solution {
    public int maxSubArray(int[] nums) {
        int prevMax = nums[0];
        int globalMax = nums[0];
        for (int i = 1; i < nums.length; i++) {
            int curr = nums[i];
            prevMax = Math.max(curr, prevMax + curr);
            globalMax = Math.max(prevMax, globalMax);
        }
        return globalMax;
    }
}