알고리즘

백준 1806번 부분합 (JAVA)

박카스마시며코딩 2024. 1. 19. 15:06

https://www.acmicpc.net/problem/1806

 

1806번: 부분합

첫째 줄에 N (10 ≤ N < 100,000)과 S (0 < S ≤ 100,000,000)가 주어진다. 둘째 줄에는 수열이 주어진다. 수열의 각 원소는 공백으로 구분되어져 있으며, 10,000이하의 자연수이다.

www.acmicpc.net

 

저는 투포인트를 통해 문제를 풀었습니다.

투포인트를 통해 해당 포인트 사이의 합을 구하고 이 합이 목표값보다 작으면 앞쪽 포인트를 크다면 뒤쪽 포인트를 늘리면서 목표값이 크면서 인덱스 사이의 값이 작은 것을 찾아 문제를 풀었습니다.

 

package BOJ.twopoint;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.StringTokenizer;

public class BOJ_1806_2 {
    public static void main(String[] args) throws Exception {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        StringTokenizer st = new StringTokenizer(br.readLine());
        int n = Integer.parseInt(st.nextToken());
        int s = Integer.parseInt(st.nextToken());
        int[] number = new int[n];
        st = new StringTokenizer(br.readLine());
        for(int i = 0 ; i < n ;i++){
            number[i] = Integer.parseInt(st.nextToken());
        }
        int result = cal(number,n,s);
        System.out.println(result);
    }

    private static int cal(int[] number, int n, int s) {
        int sum = 0;
        int result = 0;
        int startIndex = 0;
        int endIndex = 0;
        while(true){
            if(sum < s){
                if(endIndex >= n){
                    break;
                }
                sum += number[endIndex++];
            }
            while(sum >= s){
                if(result == 0){
                    result = endIndex - startIndex ;
                }
                result = Math.min(result,endIndex - startIndex);
                sum -= number[startIndex++];
            }
        }
        return result;
    }

}

'알고리즘' 카테고리의 다른 글

백준 1343번 폴리오미노 (JAVA)  (0) 2024.01.17
백준 14916번 거스름돈 (JAVA)  (0) 2024.01.16
백준 2217번 로프 (JAVA)  (0) 2024.01.15
백준 1758번 알바생 강호 (JAVA)  (1) 2024.01.14
백준 2164번 카드2 (JAVA)  (1) 2024.01.13