알고리즘/백준풀이6. 다이나믹프로그래밍
(15) [C, C++, Java] 백준 No.1912 : 연속합
Storage Gonie
2019. 5. 15. 21:59
반응형
문제
풀이
자세한 풀이 : https://ldgeao99.tistory.com/entry/챕터3-16-DP-문제-풀이3-5-백준-No1912-연속합
# C++
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
int main()
{
int n;
cin >> n;
vector<int> a(n);
vector<int> d(n);
for (int i = 0; i < n; i++)
cin >> a[i];
d[0] = a[0];
for (int i = 1; i < n; i++)
d[i] = max(d[i-1] + a[i], a[i]);
cout << *max_element(d.begin(), d.end()) << "\n";
}
# C
#include <stdio.h>
int a[100000];
int d[100000];
int main() {
int n;
scanf("%d",&n);
for (int i=0; i<n; i++) {
scanf("%d",&a[i]);
}
for (int i=0; i<n; i++) {
d[i] = a[i];
if (i == 0) continue;
if (d[i] < d[i-1] + a[i]) {
d[i] = d[i-1] + a[i];
}
}
int ans = d[0];
for (int i=0; i<n; i++) {
if (ans < d[i]) {
ans = d[i];
}
}
printf("%d\n",ans);
return 0;
}
# Java
import java.util.*;
public class Main {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int[] a = new int[n];
for (int i=0; i<n; i++) {
a[i] = sc.nextInt();
}
int[] d = new int[n];
for (int i=0; i<n; i++) {
d[i] = a[i];
if (i == 0) {
continue;
}
if (d[i] < d[i-1] + a[i]) {
d[i] = d[i-1] + a[i];
}
}
int ans = d[0];
for (int i=0; i<n; i++) {
if (ans < d[i]) {
ans = d[i];
}
}
System.out.println(ans);
}
}
반응형