https://leetcode.com/problems/maximum-subarray/submissions/
package main
// https://leetcode.com/problems/maximum-subarray/
func main() {
// nums := []int{-2,1,-3,4,-1,2,1,-5,4}
nums := []int{5, 4, -1, 7, 8}
// nums := []int{1}
maxSubArray(nums)
}
// 제출 코드
func maxSubArray(nums []int) int {
if len(nums) == 1 {
return nums[0]
}
maxSum := nums[0]
result := 0
check := 0
for check < len(nums) {
result += nums[check]
if result > maxSum {
maxSum = result
}
if result < 0 {
result = 0
}
check++
}
return maxSum
}
'Algorithm > Go' 카테고리의 다른 글
[LeetCode] Best Time to Buy and Sell Stock (0) | 2022.01.24 |
---|---|
[LeetCode] Adding Spaces to a String (0) | 2022.01.24 |
[LeetCode] Longest Common Prefix (0) | 2022.01.09 |
[LeetCode] Longest Substring Without Repeating Characters (0) | 2022.01.03 |
[LeetCode] Minimum Index Sum of Two Lists (0) | 2022.01.03 |