学习时间:
2023年1月28日
题目描述:

题解分享:
/**
* @ Author 繁华倾夏
* @ Date 2023年01月28日
*/
// 力扣(LeetCode):53. 最大子数组和
public class Solution {
public static int maxSubArray(int[] nums) { // 调用函数
int pre = 0, max = nums[0];
for (int x : nums) { // for-each循环遍历-Java特有遍历方法
pre = Math.max(pre + x, x); // 返回两个数值中最大的那个
max = Math.max(max, pre); // 返回两个数值中最大的那个
}
return max; // 返回最大值
}
// 测试用例
// 输入 nums = [-2,1,-3,4,-1,2,1,-5,4]
// 输出 6
public static void main(String[] args) {
int[] nums={-2,1,-3,4,-1,2,1,-5,4};
int re=maxSubArray(nums);
System.out.println(re);
}
}
【繁华倾夏】【每日力扣题解分享】【Day14】