一、题目描述
给定一个数组 array[1, 4, -5, 9, 8, 3, -6],在这个数字中有多个子数组,子数组和最大的应该是:[9, 8, 3],输出20,再比如数组为[1, -2, 3, 10, -4, 7, 2, -5],和最大的子数组为[3, 10, -4, 7, 2],输出18。
实现代码
public class Solution {
public int FindGreatestSumOfSubArray(int[] array) {
if(array.length == 0)return 0;
int max = array[0];
int cur = array[0] ;
for(int i = 1;i < array.length ;i++){
cur = (cur < 0)?array[i]:cur + array[i];
max = Math.max(max,cur);
}
return max;
}
}
二 用单调实现
package Lists;
/**
* 〈一句话功能简述〉<br>
* 〈子数组和〉
*
* @author zhaohaiming
* @create 2022/8/8
* @since 1.0.0
*/
public class ArraySum {
public static int getArraySum (int[] array, int K ){
if(null == array || array.length == 0 || K <= 0 ){
return 0;
}
int len = 0;
int L = 0;
int R = 0;
int wSum = array[0];
while (R < array.length){
if(wSum == K){
len = Math.max(len,R - L +1);
wSum -=array[L++];
}else if(wSum< K){
R++;
//说明越界了 中断
if(R == array.length){
break;
}
wSum +=array[R];
}else {
wSum -= array[L++];
}
}
return len;
}
public static void main(String[] args) {
int array[] = {1,3,4,2,6,3,2,8};
System.out.println(getArraySum(array,8));
}
}