【Leetcode解題】53. Maximum Subarray
題目
- 題目連結
- 目標函式 :
maxSubArray(nums)- Input :
nums: List[int] - Output :
int
- Input :
解題概念
- 題意 : 給定一整數陣列
nums,找出擁有最大總和的 Subarray,並將該總和回傳 - Subarray 定義 : 一陣列中連續非空的元素序列
我的寫法
- 想法 : 使用 Dynamic Programming 中的 Kadane’s Algorithm
- 變數 :
round_max: 紀錄當前回合的總和最大值result_max: 紀錄目前比較過之回合的最大值
- 每回合要做的事 :
- 更新
round_max: 需要去判斷num是否要加入到 Subarray 中- 方式 : 比較
num與 (round_max+num) 的大小,並將較大者更新到round_max中
- 方式 : 比較
- 更新
result_max: 比較round_max與result_max的大小,並將較大者更新到result_max中
- 更新
- 變數 :
- 程式碼 :
1
2
3
4
5
6
7
8def maxSubArray(self, nums):
round_max = 0
result_max = -10 ** 4 - 1
for num in nums:
round_max = max(round_max + num, num)
result_max = max(result_max, round_max)
return result_max - 成效 :
- Time Complexity : $O(n)$
- Runtime: 567 ms (faster than 75.86%)
- Memory Usage: 26.2 MB (more than 86.7%)
解答 or 其他優秀寫法
- 想法 : 與我想法類似
本部落格所有文章除特別聲明外,均採用 CC BY-NC-SA 4.0 許可協議。轉載請註明來自 Robin's Tech Blog!


