From ec2486d3ef84941e274444c363432ee5e827e7c7 Mon Sep 17 00:00:00 2001 From: HarryHa <627430775@qq.com> Date: Thu, 1 Mar 2018 21:16:34 +0800 Subject: [PATCH] =?UTF-8?q?Update=20Leetcode=20=E9=A2=98=E8=A7=A3.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit maxSubArray优化代码,没有必要初始化一个n长度的数组 --- notes/Leetcode 题解.md | 12 +++++------- 1 file changed, 5 insertions(+), 7 deletions(-) diff --git a/notes/Leetcode 题解.md b/notes/Leetcode 题解.md index fb9d66b3..9c4ffa7e 100644 --- a/notes/Leetcode 题解.md +++ b/notes/Leetcode 题解.md @@ -2379,13 +2379,11 @@ class NumArray { ```java public int maxSubArray(int[] nums) { - int n = nums.length; - int[] sum = new int[n]; - sum[0] = nums[0]; - int max = sum[0]; - for(int i = 1; i < n; i++){ - sum[i] = (sum[i-1] > 0 ? sum[i-1] : 0) + nums[i]; - max = Math.max(max, sum[i]); + int max = nums[0]; + int oldsum = nums[0]; + for (int i = 1; i < nums.length; i++) { + oldsum = (oldsum > 0 ? oldsum: 0) + nums[i]; + max = Math.max(max, oldsum); } return max; }