NC19 连续子数组的最大和

package NC;

/**
* NC19 连续子数组的最大和
* 输入一个长度为n的整型数组a,数组中的一个或连续多个整数组成一个子数组。求所有子数组的和的最大值。要求时间复杂度为 O(n).
*
* @author Tang
* @date 2021/10/12
*/
public class FindGreatestSumOfSubArray {

/**
* 动态规划
* x: 从后往前遍历数组
* f(x): 以x元素开头最大连续的值
* f(x) = MAX(x, f(x+1)+x) //记录一个索引index
* base: f(n) = n
*
* @param array
* @return
*/
public int FindGreatestSumOfSubArray(int[] array) {

//构建dp tables
int[] dpTables = new int[array.length];

int max = 0;
for(int i = array.length-1; i >= 0; i--) {
if(i == array.length-1) {
dpTables[i] = array[i];
max = array[i];
continue;
}

dpTables[i] = Math.max(array[i], dpTables[i+1]+array[i]);
max = Math.max(max, dpTables[i]);
}
return max;

}

public static void main(String[] args) {


}

}
原文地址:https://www.cnblogs.com/ttaall/p/15398217.html