From 1436d014330d81753161ba75d93a3a2c80e03c2b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E4=B8=80=E6=96=87?= <30338551+YiwenXie@users.noreply.github.com> Date: Wed, 12 May 2021 22:34:43 +0900 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=200053.=E6=9C=80=E5=A4=A7?= =?UTF-8?q?=E5=AD=90=E5=BA=8F=E5=92=8C.md=20Java=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0053.最大子序和.md | 20 +++++++++++++++++++- 1 file changed, 19 insertions(+), 1 deletion(-) diff --git a/problems/0053.最大子序和.md b/problems/0053.最大子序和.md index b8a9d748..b8b11a57 100644 --- a/problems/0053.最大子序和.md +++ b/problems/0053.最大子序和.md @@ -139,7 +139,25 @@ public: Java: - +```java +class Solution { + public int maxSubArray(int[] nums) { + if (nums.length == 1){ + return nums[0]; + } + int sum = Integer.MIN_VALUE; + int count = 0; + for (int i = 0; i < nums.length; i++){ + count += nums[i]; + sum = Math.max(sum, count); // 取区间累计的最大值(相当于不断确定最大子序终止位置) + if (count <= 0){ + count = 0; // 相当于重置最大子序起始位置,因为遇到负数一定是拉低总和 + } + } + return sum; + } +} +``` Python: