본문 바로가기
PS 문제 풀이/SWEA

[SWEA] 3819 최대 부분 배열

by 까망 하르방 2021. 2. 28.
반응형

출처: [SWEASW 문제해결 심화 - Ad Hoc Algorithms

 Input 

2

1

3

5

1

3

-5

3

6

 

 Output 

#1 3

#2 9

연속되는 부분 배열의 최대합을 구하는 문제


import java.util.Scanner;
 
public class Solution {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
         
        int T = Integer.parseInt(sc.next());
         
        for(int tc=1; tc<=T; tc++) {
             
            int N = Integer.parseInt(sc.next());
            int[] arr = new int[N];
            for(int i=0; i<N; i++) {
                arr[i] = Integer.parseInt(sc.next());
            }
             
            System.out.print("#" + tc + " ");
            System.out.println(findMaxSubArray(arr));
        }
    }
 
    private static int findMaxSubArray(int[] A) {
        int N = A.length;
        int answer = Integer.MIN_VALUE;
        int partialSum = 0;
         
        for(int i=0; i<N; i++) {
            partialSum = Math.max(partialSum, 0) + A[i];
            answer = Math.max(partialSum, answer);
        }
         
        return answer;
    }
}

 

반응형

'PS 문제 풀이 > SWEA' 카테고리의 다른 글

[SWEA] 1954 달팽이  (0) 2021.03.01
[SWEA] 3816 아나그램  (0) 2021.03.01
[SWEA] 2814 최장경로  (0) 2021.02.27
[SWEA] 1768 숫자야구게임  (0) 2021.02.27
[SWEA] 4006 고속도로 건설 2  (0) 2021.02.27

댓글