/**
*面试题42:连续子数组的最大和
* 输入一个整型数组,数组里有正数也有负数。数组中的一个或连续多个整数组成
* 一个子数组。求所有子数组的和的最大值。要求时间复杂度为 O(n).
* @author
* @create 2021-04-01 19:38
*/
public class Solution42 {
public static void main(String[] args) {
int[] arr = {1,-2,3,10,-4,7,2,-5};
int res = findGreatestSumOfSubArray(arr);
System.out.println(res);
}
/**
*动态规划:dp数组里存的是前面连续子数组的和,如果和>0,可以继续向后
*累加,否则就置为当前值
* @param array
* @return
*/
public static int findGreatestSumOfSubArray(int[] array) {
int[] dp = new int[array.length+1];
int max = Integer.MIN_VALUE;
for (int i = 1; i < dp.length; i++) {
if (dp[i-1] >=0){
dp[i] = dp[i-1] + array[i-1];
}else {
dp[i] = array[i-1];
}
max = Math.max(dp[i], max);
}
return max;
}
}
【剑指Offer】面试题42:连续子数组的最大和
最新推荐文章于 2023-06-08 00:15:24 发布