public class Solution { public int MaxSubArray(int[] nums) { int max = int.MinValue; int sum = 0; for (int i = 0; i < nums.Length; i++) { if (sum < 0) { sum = nums[i]; } else { sum += nums[i]; } if (sum > max) { max = sum; } } return max; } }
https://leetcode.com/problems/maximum-subarray/#/description
补充一个python的实现:
1 import sys 2 class Solution: 3 def maxSubArray(self, nums: 'List[int]') -> 'int': 4 sums = 0 5 maxsum = -sys.maxsize 6 n = len(nums) 7 for i in range(n): 8 if sums < 0: 9 sums = nums[i] 10 maxsum = max(maxsum,nums[i])#使用当前值更新最大值 11 else: 12 sums += nums[i] 13 maxsum = max(maxsum,sums)#使用当前连续和更新最大值 14 return maxsum
算法思路:贪心法。