240229 연속된 부분 수열의 합

Jongleee·2024년 2월 29일
0

TIL

목록 보기
508/737
public int[] solution(int[] sequence, int k) {
	int left = 0;
	int right = 0;
	int minLength = Integer.MAX_VALUE;
	int[] answer = new int[2];
	int currentSum = 0;

	while (right < sequence.length) {
		currentSum += sequence[right];
		while (currentSum > k) {
			currentSum -= sequence[left];
			left++;
		}
		if (currentSum == k) {
			int currentLength = right - left + 1;
			if (currentLength < minLength) {
				minLength = currentLength;
				answer[0] = left;
				answer[1] = right;
			}
		}
		right++;
	}

	return answer;
}

출처:https://school.programmers.co.kr/learn/courses/30/lessons/178870

0개의 댓글