链接:https://leetcode-cn.com/problems/maximum-subarray
给定一个整数数组 nums ,找到一个具有最大和的连续子数组(子数组最少包含一个元素),返回其最大和。
示例 1:
输入:nums = [-2,1,-3,4,-1,2,1,-5,4]
输出:6
解释:连续子数组 [4,-1,2,1] 的和最大,为 6 。
示例 2:
输入:nums = [1]
输出:1
示例 3:
输入:nums = [0]
输出:0
示例 4:
输入:nums = [-1]
输出:-1
示例 5:
输入:nums = [-100000]
输出:-100000
本题的知识点(自己学到的):
Math.max();
其是用来比较括号中两个数的大小,并返回较大的值;
这个应该能用到,注意一下;
普通的for循环
class Solution {
public int maxSubArray(int[] nums) {
int add=0,tes=nums[0];
for(int i=0;i<nums.length;i++)
{
add=Math.max(nums[i],nums[i]+add);
tes=Math.max(add,tes);
}
return tes;
}
}
add=Math.max(nums[i],nums[i]+add);
此处要注意数组下标越界,当时写的时候也是自己脑袋抽了,这里面比较的是此时的数组的值和与前面相加后的值,而不能写成nums[i]+num[add],这本身就是一个错误的写法。
增强型for循环
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;
}
}