π [λ°±μ€μκ³ λ¦¬μ¦ νμ΄] 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