力扣简53 最大子序和

用到了动态规划,看了题解写了以下思路

 

class Solution {

public int maxSubArray(int[] nums) {

// double res=-1E4;
// System.out.println(res); //科学计数法 只能是double float型
int res=-10000; //存储最后的结果 本来设置Integer.MIN_VALUE 但是这样当首元素为负数时 直接溢出
int[] max=new int[nums.length]; //以当前位置下元素为结尾的最大值
int preMax=-10000;
for(int i=0;i<nums.length;i++) { //求出max数组
if(nums[i]>nums[i]+preMax) {
max[i]=nums[i];
}
else {
max[i]=nums[i]+preMax;
}
preMax=max[i];
if(res<max[i]) {
res=max[i];
}
}

return res ;

}


//public static void main(String[] args) {
//
// Solution solution=new Solution();
// int[] nums= {-1,0,-1,-1};
// int res=solution.maxSubArray(nums);
//// for(int i:max) { //测试max数组
//// System.out.println(i);
//// }
// System.out.println(res);
// }

}

答案调用了math.max函数 且没有用数组保存结果 因为只需要知道前一个的结果 如下:

class Solution {
public int maxSubArray(int[] nums) {
int pre = 0, maxAns = nums[0];
for (int x : nums) {
pre = Math.max(pre + x, x);
maxAns = Math.max(maxAns, pre);
}
return maxAns;
}
}

 

posted @ 2021-10-31 16:37  Ssshiny  阅读(35)  评论(1)    收藏  举报