leet-code/src/main/java/leetcode/editor/cn/MaximumSubarray.java

79 lines
1.5 KiB
Java
Raw Normal View History

2021-07-06 23:40:38 +08:00
//给定一个整数数组 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
//
//
//
//
// 提示:
//
//
// 1 <= nums.length <= 3 * 104
// -105 <= nums[i] <= 105
//
//
//
//
// 进阶:如果你已经实现复杂度为 O(n) 的解法,尝试使用更为精妙的 分治法 求解。
// Related Topics 数组 分治 动态规划
// 👍 3368 👎 0
package leetcode.editor.cn;
//53:最大子序和
class MaximumSubarray {
public static void main(String[] args) {
//测试代码
Solution solution = new MaximumSubarray().new Solution();
}
//力扣代码
//leetcode submit region begin(Prohibit modification and deletion)
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;
}
}
//leetcode submit region end(Prohibit modification and deletion)
}