From ed660c8b5760a2b515ab7305a9e3680916c56d3b Mon Sep 17 00:00:00 2001 From: "huangge1199@hotmail.com" Date: Tue, 6 Jul 2021 23:40:38 +0800 Subject: [PATCH] =?UTF-8?q?53:=E6=9C=80=E5=A4=A7=E5=AD=90=E5=BA=8F?= =?UTF-8?q?=E5=92=8C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../leetcode/editor/cn/MaximumSubarray.java | 79 +++++++++++++++++++ .../leetcode/editor/cn/MaximumSubarray.md | 53 +++++++++++++ 2 files changed, 132 insertions(+) create mode 100644 src/main/java/leetcode/editor/cn/MaximumSubarray.java create mode 100644 src/main/java/leetcode/editor/cn/MaximumSubarray.md diff --git a/src/main/java/leetcode/editor/cn/MaximumSubarray.java b/src/main/java/leetcode/editor/cn/MaximumSubarray.java new file mode 100644 index 0000000..2bb8699 --- /dev/null +++ b/src/main/java/leetcode/editor/cn/MaximumSubarray.java @@ -0,0 +1,79 @@ +//给定一个整数数组 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) + +} \ No newline at end of file diff --git a/src/main/java/leetcode/editor/cn/MaximumSubarray.md b/src/main/java/leetcode/editor/cn/MaximumSubarray.md new file mode 100644 index 0000000..9f069f7 --- /dev/null +++ b/src/main/java/leetcode/editor/cn/MaximumSubarray.md @@ -0,0 +1,53 @@ +

给定一个整数数组 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
+
+ +

 

+ +

提示:

+ + + +

 

+ +

进阶:如果你已经实现复杂度为 O(n) 的解法,尝试使用更为精妙的 分治法 求解。

+
Related Topics
  • 数组
  • 分治
  • 动态规划
  • \n
  • 👍 3368
  • 👎 0
  • \ No newline at end of file