[Eric's 백준] 1806번 - 부분합 - Java

Eric·2023년 1월 17일
0

BoJ(백준)

목록 보기
3/6

저는 투 포인터를 이용해서 문제를 풀어보았습니다.

import java.util.Scanner;

public class N1806 {
    public static void main(String[] args) {
        N1806 T = new N1806();
        Scanner kb = new Scanner(System.in);
        int n = kb.nextInt();
        int s = kb.nextInt();
        // 투포인터를 사용하기위해서 배열을 한칸 늘림
        int[] arr = new int[n+1];
        for (int i = 0; i < n; i++) {
            arr[i] = kb.nextInt();
        }
        System.out.println(T.solution(n, s, arr));
    }
    public int solution(int n, int s, int[] arr) {
        int len = Integer.MAX_VALUE;
        
        //lt 는 left target rt는 right target 을 의미
        // sum 이 s보다 작으면 rt값 증가 시키고, sum이 s보다 크면 lt를 증가시킴
        int lt = 0, sum = 0, rt = 0;
        while (lt <= rt && rt <= n) {
            if (sum < s) {
                sum += arr[rt++];
            } else if (sum >= s) {
                len = Math.min(len, rt - lt);
                sum -= arr[lt++];
            }
        }
        return len==Integer.MAX_VALUE ? 0 : len;
    }
}
profile
Ærlighed i små ting er ikke nogen lille ting.

0개의 댓글