[algorithm] Maximum Sum Circular Subarray

오현우·2022년 6월 27일
0

알고리즘

목록 보기
19/25
post-thumbnail

문제

Given a circular integer array nums of length n, return the maximum possible sum of a non-empty subarray of nums.

A circular array means the end of the array connects to the beginning of the array. Formally, the next element of nums[i] is nums[(i + 1) % n] and the previous element of nums[i] is nums[(i - 1 + n) % n].

A subarray may only include each element of the fixed buffer nums at most once. Formally, for a subarray nums[i], nums[i + 1], ..., nums[j], there does not exist i <= k1, k2 <= j with k1 % n == k2 % n.

Example 1:

Input: nums = [1,-2,3,-2]
Output: 3
Explanation: Subarray [3] has maximum sum 3.
Example 2:

Input: nums = [5,-3,5]
Output: 10
Explanation: Subarray [5,5] has maximum sum 5 + 5 = 10.
Example 3:

Input: nums = [-3,-2,-3]
Output: -2
Explanation: Subarray [-2] has maximum sum -2.

Constraints:

n == nums.length
1 <= n <= 3 104
-3
104 <= nums[i] <= 3 * 104

해결 방법

우리는 전에 부분 배열 최대 합 문제에 대하여 3가지 특성이 있다고 말했었다.

  1. 모든 원소가 음이 아닌 정수인 경우: 전체의 합이 정답임이 자명하다.
  2. 모든 원소가 양이 아닌 정수인 경우: 가장 큰 수 1개가 정답.
  3. 몇몇 부분 배열이 최대 합을 갖는 경우: 해당 배열의 합이 정답이다.

1, 2 케이스의 경우는 간단하게 해결이 된다.

3의 케이스만 조심하면 된다.
일반적인 카데네 알고리즘으로는 circular 한 경우는 신경쓰지 못한다. 때문에 하나의 제약 조건을 만족시킬 수 있는 방법을 도입하자.

우리는 3번째 경우에서 2가지 케이스를 생각해 볼 수 있다.

  1. 양 끝 엣지중 둘중의 하나가 포함되어있지 않거나 둘다 포함되어 있지 않은 경우
  2. 양 끝 엣지가 포함되어 있는 경우

1의 경우는 일반적인 카데네 알고리즘으로 풀 수 있다.
2의 경우는 전체의 합을 구한 뒤에 배열 중간에서 최소 합을 구한뒤 전체 합에서 빼준다.

풀이

kadene's algo

class Solution:
    def maxSubarraySumCircular(self, A: List[int]) -> int:
    
        # Method 1 : Kadane's Algorithm
        if max(A) <= 0:
            return max(A)
        
        max_sum = curr_max = min_sum = curr_min = A[0] 
        
        for i in range(1, len(A)): 
            curr_max = max(A[i], curr_max + A[i]) 
            max_sum = max(max_sum, curr_max)
            curr_min = min(A[i], curr_min + A[i]) 
            min_sum = min(min_sum, curr_min)
            
        return max(max_sum, sum(A) - min_sum)

dp algo

class Solution:
    def maxSubarraySumCircular(self, A: List[int]) -> int:
        if max(A) <= 0:
            return max(A)
        max_dp = [i for i in A]
        min_dp = [i for i in A]
        
        for i in range(1,len(A)):
            if max_dp[i-1] > 0:
                max_dp[i] += max_dp[i-1]
            if min_dp[i-1] < 0:
                min_dp[i] += min_dp[i-1]

        return max(max(max_dp), sum(A) - min(min_dp))
profile
핵심은 같게, 생각은 다르게

0개의 댓글