강의

멘토링

로드맵

인프런 커뮤니티 질문&답변

작성자 없음

작성자 정보가 삭제된 글입니다.

자바스크립트 알고리즘 문제풀이 입문(코딩테스트 대비)

4. 연속부분수열2(Two Pointers Algorithm)

이렇게 짜도 될까요? for문 하나에서 만들어 보았습니다.

작성

·

250

0

function solution(M, arr) {
  let i = 0,
    sum = 0,
    q = 0;
  answer = 0;
  for (i; i < arr.length; i++) {
    sum += arr[i];
    if (sum < M) {
      answer++;
    } else {
      if (sum === M) answer++;
      q++;
      i = q - 1;
      sum = 0;
    }
  }
  return answer;
}

let M = 5;
let arr = [1, 3, 1, 2, 3];

console.log(solution(M, arr));

퀴즈

What is the main reason why two-pointer or sliding window techniques are more efficient than nested loops?

Because it uses less memory?

Is it because the code is shorter?

Is it because it achieves O(N) time complexity in most cases?

Is it because it's not affected by the input data size?

답변 1

0

김태원님의 프로필 이미지
김태원
지식공유자

안녕하세요^^

let arr=[1, 1, 1, 1, 1];

이면 답이 12가 나와야 하는데 11이 나오네요.

 

 

작성자 없음

작성자 정보가 삭제된 글입니다.

질문하기