Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 9031523

Browse files
committed
添加 0053.最大子序和.md Scala版本
1 parent bd4f69d commit 9031523

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed

‎problems/0053.最大子序和.md‎

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -333,8 +333,41 @@ function maxSubArray(nums: number[]): number {
333333
};
334334
```
335335

336+
### Scala
336337

338+
**贪心**
339+
340+
```scala
341+
object Solution {
342+
def maxSubArray(nums: Array[Int]): Int = {
343+
var result = Int.MinValue
344+
var count = 0
345+
for (i <- nums.indices) {
346+
count += nums(i) // count累加
347+
if (count > result) result = count // 记录最大值
348+
if (count <= 0) count = 0 // 一旦count为负,则count归0
349+
}
350+
result
351+
}
352+
}
353+
```
337354

355+
**动态规划**
356+
357+
```scala
358+
object Solution {
359+
def maxSubArray(nums: Array[Int]): Int = {
360+
var dp = new Array[Int](nums.length)
361+
var result = nums(0)
362+
dp(0) = nums(0)
363+
for (i <- 1 until nums.length) {
364+
dp(i) = math.max(nums(i), dp(i - 1) + nums(i))
365+
result = math.max(result, dp(i)) // 更新最大值
366+
}
367+
result
368+
}
369+
}
370+
```
338371

339372
-----------------------
340373
<div align="center"><img src=https://code-thinking.cdn.bcebos.com/pics/01二维码一.jpg width=500> </img></div>

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /