[Coding Test] inflearn(3)

박찬영·2024년 2월 13일

Coding Test

목록 보기
16/41

1. 구간 합

구간 합은 합 배열을 이용하여 시간 복잡도를 더 줄이기 위해 사용하는 특수한 목적의 알고리즘이다.

구간 합의 핵심 이론

  • 구간 합 알고리즘을 활용하려면 먼저 합 배열을 구해야 한다.
  • 배열 A가 있을 때 합 배열 S는 다음과 같이 정의한다.

합 배열의 S 정의
S[i] = A[0] + A[1] + A[2] + ... + A[i-1] + A[i]

합 배열 S를 만드는 공식
S[i] = S[i-1] + A[i]

구간 합을 구하는 공식
S[i] - S[i-1]

2. 구간 합 실전 문제

구간 합 구하기 (백준 11659)

import java.util.Scanner;

public class P11659_구간합구하기 {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);

        int N = sc.nextInt();
        int M = sc.nextInt();
        int[] sum = new int[N + 1];
        sum[0] = 0;
        for (int i = 1; i <= N; i++) {
            sum[i] = sc.nextInt() + sum[i - 1];
        }
        while (M-- > 0) {
            System.out.println((-sum[sc.nextInt()-1]+sum[sc.nextInt()]));
        }
    }
}


3. 투 포인터 실전 문제

수들의 합 (백준 2018)

import java.util.Scanner;

public class P2018_수들의합 {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int N = sc.nextInt();
        int sum = 0;
        int count = 1;
        int start_index = 0, end_index = 0;

        while (end_index != N) {
            if (sum == N) {
                count++;
                end_index++;
                sum += end_index;
            } else if (sum > N) {
                sum -= start_index;
                start_index++;
            } else if (sum < N) {
                end_index++;
                sum += end_index;
            }
        }
        System.out.println(count);
    }
}


주몽 (백준 1940)

import java.io.*;
import java.util.StringTokenizer;

public class P1940_주몽 {
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

        int count = 0;
        int N = Integer.parseInt(br.readLine());
        int M = Integer.parseInt(br.readLine());
        String sNum = br.readLine();
        StringTokenizer st = new StringTokenizer(sNum);
        int[] aa = new int[N];
        for (int i = 0; i < N; i++) {
            aa[i] = Integer.parseInt(st.nextToken());
        }

        int start_index = 0;
        int end_index = 0;
        for (int i = 0; i < N; i++) {
            for (int j = i + 1; j < N; j++) {
                start_index = aa[i];
                end_index = aa[j];
                if (start_index + end_index == M)
                    count++;
            }
        }
        System.out.println(count);
    }
}

profile
블로그 이전했습니다 -> https://young-code.tistory.com

0개의 댓글