[leet_code] 53. Maximum Subarray

오현우·2022년 4월 6일
0
post-thumbnail

문제 내용

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

Follow up: If you have figured out the O(n) solution, try coding another solution using the divide and conquer approach, which is more subtle.

체크해야할 점

  1. 같은 숫자가 나올 수 있다.
  2. 음수가 존재한다.

해결 방법

brute force O(n^2)

단순한게 오히려 좋을 수 있다.
일단 직관적으로 생각나는 것은 크기가 1인 리스트부터 전체 크기까지 앞숫자부터

class Solution:
    def maxSubArray(self, nums: List[int]) -> int:
        # brute force
        if len(nums) == 1:
        answer = nums[0]
        	return answer
            
        for list_len in range(1, len(nums)+1): 
            for index in range(0, len(nums)-list_len+1):
                temp = sum(nums[index:index+list_len])
                answer = max(temp, answer)
        return answer

tabulation

위의 방법보다 시간복잡도를 월등히 줄일 수 있다.
연속된 합의 최대를 찾는 것에 주목하자.
우리는 그럼 처음부터 비교해 가면된다.

처음 숫자 > 2번째 숫자를 더한다 > 두번 째를 더한 것과 두번째 숫자와 비교한다 > 큰 것을 우리 메모한다. > 메모한 것들중에서 제일 큰 녀석을 뽑아낸다.

class Solution:
    def maxSubArray(self, nums: List[int]) -> int:
        dp = []
        for num in nums:
            if not dp: # 리스트의 처음 시작
                dp.append(num)
            else: # 그 이후 
                dp.append(max(dp[-1] + num, num)) 
                
        return max(dp)

공간 복잡도를 O(1) 로 바꾼 녀석

찾아보니 내 솔루션보다 더 좋게 최적화를 진행한 코드가 존재하였다.

class Solution:
    def maxSubArray(self, nums: List[int]) -> int:
        max_sum = None
        for num in nums:
            if max_sum is None:
                max_sum_until_i = num
                max_sum = max_sum_until_i
            else:
                max_sum_until_i = max(max_sum_until_i+num, num)
                max_sum = max(max_sum,max_sum_until_i,max_sum)
            
        return max_sum
profile
핵심은 같게, 생각은 다르게

0개의 댓글