Skip to content

Prepare For Coder Interview – Denny

  • Basic
  • Medium
  • Hard
  • Architect
  • Life

LeetCode: Maximum Subarray

Posted on January 12, 2018July 26, 2020 by braindenny

Maximum Subarray



Similar Problems:

  • CheatSheet: Leetcode For Code Interview
  • CheatSheet: Common Code Problems & Follow-ups
  • Tag: #inspiring, #subarray, #classic, #presum, #maxsubarraysum, #kadane

Find the contiguous subarray within an array (containing at least one number) which has the largest sum.

For example, given the array [-2,1,-3,4,-1,2,1,-5,4],
the contiguous subarray [4,-1,2,1] has the largest sum = 6.

click to show more practice.

More practice:
If you have figured out the O(n) solution, try coding another solution using the divide and conquer approach, which is more subtle.

Github: code.dennyzhang.com

Credits To: leetcode.com

Leave me comments, if you have better ways to solve.


// https://code.dennyzhang.com/maximum-subarray
// Basic Ideas: presum
// Complexity: Time O(n), Space O(n)
func maxSubArray(nums []int) int {
    if len(nums) == 0 { return -1 }
    res := -1 << 31
    min := 0
    for preSum, i :=0, 0; i<len(nums); i++ {
        preSum += nums[i]
        if (res < preSum - min) {
            res = preSum - min
        }
        if (preSum < min) { min = preSum }
    }
    return res
}
linkedin
github
slack

Post Views: 9
Posted in MediumTagged #classic, #inspiring, #subarray, kadane, maxsubarraysum, presum

Post navigation

LeetCode: Spiral Matrix II
LeetCode: Power of Two

Leave a Reply Cancel reply

Your email address will not be published.

Tags

#array #backtracking #bfs #binarytree #bitmanipulation #blog #classic #codetemplate #combination #dfs #dynamicprogramming #game #graph #greedy #heap #inspiring #interval #linkedlist #manydetails #math #palindrome #recursive #slidingwindow #stack #string #subarray #trie #twopointer #twosum binarysearch editdistance hashmap intervaldp knapsack monotone oodesign presum rectangle redo review rotatelist series sql treetraversal unionfind

Recent Posts

  • a
  • a
  • a
  • a
  • a

Recent Comments

    Archives

    Categories

    • Amusing
    • Basic
    • Easy
    • Hard
    • Life
    • Medium
    • Resource
    • Review
    • Series
    • Uncategorized
    Proudly powered by WordPress | Theme: petals by Aurorum.