1. 题目
https://leetcode.cn/problems/maximum-subarray/
53. 最大子数组和
2. 解法
2.1 解法一:借助dp数组
public static int maxSubArray(int[] nums) { int[] dp = new int[nums.length]; dp[0] = nums[0]; int result = dp[0]; for (int i = 1; i < nums.length; i++) { dp[i] = Math.max(nums[i], dp[i - 1] + nums[i]); result = Math.max(result, dp[i]); } return result; }
2.2 解法二: 不借助dp数组
public static int maxSubArray2(int[] nums) { int result = nums[0]; int pre = nums[0]; for (int i = 1; i < nums.length; i++) { pre = Math.max(nums[i], nums[i] + pre); result = Math.max(result, pre); } return result; }