Notice
Recent Posts
Recent Comments
Link
개발자는 기록이 답이다
자바(Java) 알고리즘 문제풀이 입문: 코딩테스트 대비(Array_점수 계산) 본문
https://cote.inflearn.com/contest/10/problem/02-07
(위의 링크는 인프런 로그인 후, 해당 강의를 사지 않으면 접속이 되지 않습니다)
7. 점수계산
예시 입력 1
10
1 0 1 1 1 0 0 1 1 0
예시 출력 1
10
내가 푼 풀이(Time: 158ms Memory: 27MB)
import java.util.Scanner;
public class Main {
public int solution(int n, int[] grade) {
int answer = 0;
int count = 0;
for (int i = 0; i < n; i++) {
if (grade[i] == 1)
count ++;
else
count = 0;
answer += count;
}
return answer;
}
public static void main(String[] args) {
Main T = new Main();
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int[] grade = new int[n];
for (int i = 0; i < n; i++) {
grade[i] = sc.nextInt();
}
System.out.println(T.solution(n, grade));
}
}
강의 풀이(Time: 160ms Memory: 27MB)
1. 입력을 하나씩 탐색하면서 1을 만나면 cnt를 증가시킨다.
2. 0을 만나면 cnt를 0으로 초기화 시킨다.
3. 순회를 하면서 sum에 누적시키면 된다.
import java.util.Scanner;
public class Main {
public int solution(int n, int[] arr) {
int answer = 0, cnt = 0; // answer이 sum
for (int i = 0; i < n; i++) {
if (arr[i] == 1) {
cnt++;
answer+=cnt;
}
else cnt = 0;
}
return answer;
}
public static void main(String[] args) {
Main T = new Main();
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int[] array = new int[n];
for (int i = 0; i < n; i++) {
array[i] = sc.nextInt();
}
System.out.println(T.solution(n, array));
}
}
'알고리즘 > 인프런 - Java알고리즘 입문' 카테고리의 다른 글
자바(Java) 알고리즘 문제풀이 입문: 코딩테스트 대비(Array_격자판 최대합) (1) | 2023.09.06 |
---|---|
자바(Java) 알고리즘 문제풀이 입문: 코딩테스트 대비(Array_등수 구하기) (0) | 2023.09.05 |
자바(Java) 알고리즘 문제풀이 입문: 코딩테스트 대비(Array_뒤집은 소수) (0) | 2023.09.05 |
자바(Java) 알고리즘 문제풀이 입문: 코딩테스트 대비(Array_에라토스테네스 체) (0) | 2023.09.05 |
자바(Java) 알고리즘 문제풀이 입문: 코딩테스트 대비(Array_피보나치 수열) (0) | 2023.09.04 |