πŸ“– [λ°±μ€€μ•Œκ³ λ¦¬μ¦˜ 풀이] 1912 연속합

πŸ“– 문제

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

πŸ” 접근법

μ—°μ†λ˜λŠ” λͺ‡ 개의 수λ₯Ό μ„ νƒν•΄μ„œ ꡬ할 수 μžˆλŠ” ν•© 쀑 κ°€μž₯ 큰 합을 ꡬ해야함.

μˆ«μžκ°€ μ—°μ†λ˜λŠ” 합을 κ΅¬ν•˜λŠ” κ²ƒμ΄λ―€λ‘œ λ‹€μŒ 연속 λ˜λŠ” 수λ₯Ό ν•©ν•˜μ—¬ 더 큰 μˆ«μžκ°€ ν•΄λ‹Ή n번째 μˆ˜κΉŒμ§€ μ—°μ†μœΌλ‘œ λ”ν•˜λŠ” ν•©μ˜ μ΅œλŒ€ 값이닀.

μ—°μ†ν•΄μ„œ λ”ν•΄μ§€λŠ” 값보닀 ν˜„μž¬μ˜ μˆ«μžμ—μ„œ μƒˆλ‘œ μ‹œμž‘ν•˜λŠ” μˆ˜κ°€ 더 크닀면 ν•΄λ‹Ή λ²ˆμ§Έμ—μ„œ 연속합을 λ‹€μ‹œ μ‹œμž‘ν•œλ‹€.

d[i] = Math.max(d[i-1] + nums[i], nums[i]);

계속 λ‹€μŒ 숫자λ₯Ό λ”ν•΄λ‚˜κ°€λ‹€κ°€ 숫자λ₯Ό λ”ν•˜μ§€ μ•Šκ³  μƒˆλ‘œ μ‹œμž‘ν•˜λŠ” μˆ˜κ°€ 크닀면

연속합을 μƒˆλ‘œ μ‹œμž‘ν•œλ‹€.

πŸ’» μ½”λ“œ

package problem.dynamic.Q1912;
import java.io.*;

public class Main_1912 {
    public static int n;
    public static int[] d;
    public static void main(String[] args) throws IOException {
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
        int nums[] = input();
        int answer = solve(nums);
        bw.write(Integer.toString(answer));
        bw.flush();
        bw.close();
    }
    public static int solve(int[] nums){
        int max = Integer.MIN_VALUE;
        for(int i=1; i<=n; i++){
            d[i] = Math.max(d[i-1] + nums[i], nums[i]);
            max = Math.max(max,d[i]);
        }
        return max;
    }
    public static int[] input() throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        n = Integer.parseInt(br.readLine());
        d = new int[n+1];
        String temps[] = br.readLine().split(" ");
        int nums[] = new int[n+1];
        for(int i=1; i<=n; i++)
            nums[i] = Integer.parseInt(temps[i-1]);
        return nums;
    }
}

Written on April 22, 2020