一.问题描述
给你一个整数数组 nums ,请你找出一个具有最大和的连续子数组(子数组最少包含一个元素),返回其最大和。
子数组 是数组中的一个连续部分。
示例 1:
输入:nums = [-2,1,-3,4,-1,2,1,-5,4]
输出:6
解释:连续子数组 [4,-1,2,1] 的和最大,为 6 。
二.示例代码
public class MaximumSubarraySum {
public static void main(String[] args) {
int[] nums = new int[]{-2, 1, -3, 4, -1, 2, 1, -5, 4};
int result = maximumSubarraySum(nums);
System.out.println(result);
}
private static int maximumSubarraySum(int[] nums) {
int pre = 0, max = nums[0];
for (int num : nums) {
pre = Math.max(num, pre + num);
max = Math.max(max, pre);
}
return max;
}
}