Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum.
A subarray is a contiguous part of an array.
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 <= 105
- -104 <= nums[i] <= 104
주어진 배열에서 연속된 숫자의 합 중 가장 큰 값을 반환이 목표이다.
최초 1회 2중 for문을 통해 작성했으나 채점 기준 변경으로 timeout이 발생하여
기존 로직을 stack을 사용하는 것으로 변경하였다.
# 53. Maximum Subarray
class Solution:
def maxSubArray(self, nums: List[int]) -> int:
stack = []
list =- float('inf')
for i in nums:
if sum(stack) + i < i:
stack = []
stack.append(i)
list = max(list, sum(stack))
return list
# 1st TimeOut
# class Solution:
# def maxSubArray(self, nums: 'List[int]') -> 'int':
# max = nums[0]
# for i in range(0, len(nums)):
# sum = 0
# for j in range(i, len(nums)):
# sum += nums[j]
# if sum > max:
# max = sum
# return max
# Change scoring criteria
문제 출처 : https://leetcode.com/problems/maximum-subarray/
Maximum Subarray - LeetCode
Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.
leetcode.com
Github : https://github.com/kkkkang1009/leetcode/blob/master/leetcode_53.py
GitHub - kkkkang1009/leetcode: leetcode
leetcode. Contribute to kkkkang1009/leetcode development by creating an account on GitHub.
github.com
'IT > LeetCode' 카테고리의 다른 글
[LeetCode] 62. Unique Paths (0) | 2022.08.17 |
---|---|
[LeetCode] 58. Length of Last Word (0) | 2022.08.15 |
[LeetCode] 38. Count and Say (0) | 2022.07.22 |
[LeetCode] 35. Search Insert Position (0) | 2022.07.22 |
[LeetCode] 28. Implement strStr() (0) | 2022.07.22 |
댓글