[2018번] 연속된 자연수의 합 ( 메모리 초과 )

Loopy·2023년 11월 21일
1

코테 문제들

목록 보기
7/113


✅ 메모리 초과

합 배열 사용

메모리 초과

문제에서 요구하는 메모리 : 32MB
문제에서 입력받는 데이터 : 10,000,000 개
  
최악의 case일 때, 10,000,000 * 4 = 40,000,000 (40MB)

따라서, 메모리 초과가 발생함! -> 배열 사용 불가

✅ if-else 와 if 문

if-else문 사용if문 사용

왜 if 문을 쓰면 답이 되지 않는지 살펴보자.

[ if - else 문 ]
while 의 조건문인 (endIndex != input) 이 되기 바로 전에 검사하는 if - else 문에 첫 번째 if 문에서 endIndex ++; 를 해주고 다른 else 문은 검사하지 않고 바로 while 문으로 넘어가서 조건이 false가 되어 탈출한다.

[ if 문 ]
첫 번째 if 문에서 endIndex ++; 를 해주고 두 번째 if 문에서 startIndex ++; 를 해준 다음 세 번째 if문에서 count ++ 와 나머지 것들도 다 증가시키고 while 문으로 넘어가서 false 가 되어 탈출한다. 따라서, if문을 쓰려면 각 if 문에다 continue를 넣어 if 문이 끝나면 while이 false 인지 check 해줘야 한다.

  while (endIndex < input) {
			if (sum < input) {
				endIndex++;
				sum += endIndex;
				continue;
			}
			if (sum > input) {
				sum -= startIndex;
				startIndex++;
				continue;
			}
			if (sum == input) {
				count++;
				endIndex++;
				sum += endIndex;
				continue;
			}
		}

✅ 코드

import java.util.Scanner;

public class do_11_21_ans {
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		int input = sc.nextInt();
		int count = 1, startIndex = 1, endIndex = 1, sum = 1;

		while (endIndex < input) {
			if (sum < input) {
				endIndex++;
				sum += endIndex;
			} else if (sum > input) {
				sum -= startIndex;
				startIndex++;
			} else {
				count++;
				endIndex++;
				sum += endIndex;
			}
		}
		System.out.println(count);
	}
}


profile
잔망루피의 알쓸코딩

0개의 댓글