From a8d3874f550794df371ecb762cb4e391808e75b3 Mon Sep 17 00:00:00 2001 From: Yuki Chen <826992207@qq.com> Date: Wed, 31 Aug 2022 16:44:44 +0800 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A00053.=E6=9C=80=E5=A4=A7?= =?UTF-8?q?=E5=AD=90=E5=BA=8F=E5=92=8C=EF=BC=88=E5=8A=A8=E6=80=81=E8=A7=84?= =?UTF-8?q?=E5=88=92=EF=BC=89=E7=A9=BA=E9=97=B4=E5=A4=8D=E6=9D=82=E5=BA=A6?= =?UTF-8?q?=E4=B8=BAO(1)=E7=9A=84=E8=A7=A3=E6=B3=95=20Java=E7=89=88?= =?UTF-8?q?=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0053.最大子序和(动态规划).md | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/problems/0053.最大子序和(动态规划).md b/problems/0053.最大子序和(动态规划).md index 00f3eb84..23d23400 100644 --- a/problems/0053.最大子序和(动态规划).md +++ b/problems/0053.最大子序和(动态规划).md @@ -120,6 +120,20 @@ Java: return res; } ``` +```Java +//因为dp[i]的递推公式只与前一个值有关,所以可以用一个变量代替dp数组,空间复杂度为O(1) +class Solution { + public int maxSubArray(int[] nums) { + int res = nums[0]; + int pre = nums[0]; + for(int i = 1; i < nums.length; i++) { + pre = Math.max(pre + nums[i], nums[i]); + res = Math.max(res, pre); + } + return res; + } +} +``` Python: ```python