Leecode no.53 最大子序和

package leecode;

/**
*
* 53. 最大子序和
*
* 给定一个整数数组 nums ,找到一个具有最大和的连续子数组(子数组最少包含一个元素),返回其最大和。
*
* @author Tang
* @date 2021/9/7
*/
public class MaxSubArray {

/**
* 动态规划
* x :数组中遍历到的每个元素
* f(x) :以某个元素开头到数组结尾这段长度的最大值
* f(x) = MAX( x, f(y) + x ); y代表x的下标位置+1
* @param nums
* @return
*/
public int maxSubArray(int[] nums) {
if(nums.length == 0) {
return 0;
}

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

//倒序处理
for(int i = nums.length - 1; i >= 0; i--) {
if(i == nums.length - 1) {
tables[i] = nums[i];
continue;
}
tables[i] = Math.max(nums[i], tables[i+1] + nums[i]);
}

int max = Integer.MIN_VALUE;
for (int value : tables) {
if(max < value) {
max = value;
}
}
return max;

}

public static void main(String[] args) {

}

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