Maximum Subarray - Leetcode
Problem statement:
Given an integer array nums, find the contiguous subarray (containing at least one number) with the largest sum and return its sum.
Example:
Input:
[-2,1,-3,4,-1,2,1,-5,4]
Expected output:
6
Explanation:
The subarray [4,-1,2,1] has the largest sum = 6.
If you would like to solve the problem on Leetcode, here is the link to the problem: https://leetcode.com/problems/maximum-subarray/
Golang Solution:
func maxSubArray(nums []int) int {
maxSoFar, curSum := nums[0], 0
j := 0
for j < len(nums) {
curSum = curSum + nums[j]
if curSum > maxSoFar {
maxSoFar = curSum
}
if curSum < 0 {
curSum = 0
}
j += 1
}
return maxSoFar
}
