From 9031523bbb334cb2190b17f12333d3a5f1edda53 Mon Sep 17 00:00:00 2001 From: ZongqinWang <1722249371@qq.com> Date: Sat, 11 Jun 2022 16:40:33 +0800 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=20Scala=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0053.最大子序和.md | 33 ++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) diff --git a/problems/0053.最大子序和.md b/problems/0053.最大子序和.md index 73cac244..4971133f 100644 --- a/problems/0053.最大子序和.md +++ b/problems/0053.最大子序和.md @@ -333,8 +333,41 @@ function maxSubArray(nums: number[]): number { }; ``` +### Scala +**贪心** +```scala +object Solution { + def maxSubArray(nums: Array[Int]): Int = { + var result = Int.MinValue + var count = 0 + for (i <- nums.indices) { + count += nums(i) // count累加 + if (count > result) result = count // 记录最大值 + if (count <= 0) count = 0 // 一旦count为负,则count归0 + } + result + } +} +``` + +**动态规划** + +```scala +object Solution { + def maxSubArray(nums: Array[Int]): Int = { + var dp = new Array[Int](nums.length) + var result = nums(0) + dp(0) = nums(0) + for (i <- 1 until nums.length) { + dp(i) = math.max(nums(i), dp(i - 1) + nums(i)) + result = math.max(result, dp(i)) // 更新最大值 + } + result + } +} +``` -----------------------