Leetcode - Median of Two Sorted Arrays
Leetcode - 3Sum

Leetcode - Maximum Subarray

violet posted @ 5 年前 in 算法 with tags Algorithm array Golang , 227 阅读

https://leetcode.com/problems/maximum-subarray/

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.

 

This problem... suggest reciting the answer.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
func maxSubArray(arr []int) int {
    maxEnding := arr[0]
    maxSofar := arr[0]
     
    for i := 1; i < len(arr); i++ {
        maxEnding = max(arr[i], arr[i]+maxEnding)
        maxSofar = max(maxSofar, maxEnding)
    }
 
    return maxSofar
}
 
func max(a, b int) int {
    if a < b {
        return b
    }
 
    return a
}

One comment in discussion:

interesting fact: a problem solved by a computer professor in 1984, now become an easy level problem in Leetcode in 2016/2017...

Smile and take a breath.

 


登录 *


loading captcha image...
(输入验证码)
or Ctrl+Enter