53. 最大子序和
自己做题的思路写在了代码里:P
class Solution {
public int maxSubArray(int[] nums) {
//dp
int[] dp = new int[nums.length];//dp数组 表示在i 位置的最大自序和为dp[i]
Arrays.fill(dp, Integer.MIN_VALUE);
dp[0] = nums[0];//把除了dp[0] 以外的设置为非0, 这题求最大,所以我把他们设为最小值。-22222222222
int res = nums[0];
for(int i = 1; i < dp.length; i++){//遍历背包
dp[i] = Math.max(dp[i-1] + nums[i], nums[i]);//很好理解,就是前面的nums[i] 都相加,每次dp数组保留最大的。比如dp[i-1] + nums[i] 是负的,nums[i] 是正的,这时候dp[i] 取这个正的值
res = Math.max(dp[i], res);//结果,取最大的dp[i]
}
// return dp[nums.length-1]; // 不是返回最后一个,是返回dp数组最大的那一个
return res;
}
}
198. 打家劫舍 I
c
