Leetcode - Median of Two Sorted Arrays
Leetcode - 3Sum

Leetcode - Maximum Subarray

violet posted @ Mar 29, 2020 06:52:20 AM in 算法 with tags Algorithm array Golang , 203 阅读

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.

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