题目传送地址: ​​https://leetcode.cn/problems/maximum-subarray/​

Leetcode53. 最大子数组和_子数组


代码如下:

class Solution {

public static int maxSubArray(int[] nums) {
int maxValue = Integer.MIN_VALUE;
HashMap<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
int i1 = maxSubList(i, nums,map);
if (i1 > maxValue) {
maxValue = i1;
}
}
return maxValue;

}

//以位置i的元素结尾, 的最大连续子数组之和
public static int maxSubList(int i, int[] nums, Map<Integer, Integer> map) {
int result;
if (i == 0) {
return nums[0];
}
int i1;
if (map.containsKey(i-1)) {
i1 = map.get(i-1);
}else{
i1 = maxSubList(i - 1, nums, map);
}
if (i1 > 0) {
result = i1 + nums[i];
} else {
result = nums[i];
}
map.put(i,result);
return result;
}


}