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