Maximum Subarray
53. Maximum Subarray
μ£Όμ΄μ§ μ μ λ°°μ΄ nums
μμ μ°μμ μΈ νμ λ°°μ΄μ ν© μ€
κ°μ₯ ν° κ°μ ꡬνλλ‘ μμ±νλΌ.
νμ λ°°μ΄μ μ°μμ μΈ λ°°μ΄μ΄λ€.
Example 1:
Input: nums = [-2,1,-3,4,-1,2,1,-5,4]
Output: 6
Explanation: [4,-1,2,1] has the largest sum = 6.
Example 2:
Input: nums = [1]
Output: 1
Example 3:
Input: nums = [5,4,-1,7,8]
Output: 23
Constraints:
1 <= nums.length <= 10^5
-10^4 <= nums[i] <= 10^4
Solution
class Solution {
func maxSubArray(_ nums: [Int]) -> Int {
var nums = nums
for index in 1..<nums.count {
if nums[index - 1] > 0 {
nums[index] += nums[index - 1]
}
}
return nums.max() ?? 0
}
}
μ
λ ₯κ°μΌλ‘ λ€μ΄μ¨ nums
λ₯Ό μ§μλ³μ nums
μ λ°μ μ΄κΈ°ννμλ€.
μ°μμ μΈ νμ λ°°μ΄ μ€μμ κ°μ₯ ν° κ°μ ꡬνλ©΄ λκΈ° λλ¬Έμ
nums[index - 1]
μ΄ μμμΈμ§ νμΈνλ 쑰건μ μΆκ°νμλ€.
μμλΌλ©΄ κ°μ λν΄ nums[index]
μ λ£μ΄μ€λ€.
λ°λ³΅λ¬Έμ λͺ¨λ λκ³ λλ©΄ μ°μ°μ΄ λλ λ°°μ΄ nums
κ° λμμ κ²μ΄λ€.
λ°°μ΄μ μ΅λκ°μ΄ λ¬Έμ μμ μꡬν κ°μ΄ λλ€.
π Reference
LeetCode-53-MaximumSubarray