package com.leetcode.leetcode.licm;
/**
* @description:
* @author: licm
* @create: 2021-07-27 09:51
**/
public class Lc面试题1617连续数列 {
/**
* dp
* <p>
* 1. 确定dp含义 当前下标对应的最大值
* 2. 递推公式 Math.max(nums[i],dp[i-1]+nums[i])
* 3. 初始化
* 4。确定遍历顺序
* 4. 推导结果
*
* @param nums
* @return
*/
public static int maxSubArray(int[] nums) {
if (nums.length == 0) {
return 0;
}
int[] dp = new int[nums.length];
dp[0] = nums[0];
for (int i = 1; i < nums.length; i++) {
dp[i] = Math.max(nums[i], dp[i - 1] + nums[i]);
}
int res = Integer.MIN_VALUE;
for (int i = 0; i < dp.length; i++) {
res = res < dp[i] ? dp[i] : res;
}
return res;
}
public static void main(String[] args) {
int[] nums = {-2, 1, -3, 4, -1, 2, 1, -5, 4};
System.out.println(maxSubArray(nums));
}
}
不会,我可以学;落后,我可以追赶;跌倒,我可以站起来!