연속하는 숫자의 최대값 구하기, 자바스크립트

라용·2022년 10월 1일
0

위코드 - 스터디로그

목록 보기
67/100

위코드 코드카타를 정리한 내용입니다.

문제

숫자로 이루어진 리스트 nums 를 인자로 주고 그 안의 연속적인 요소를 더했을 때 가장 큰 값을 찾아 리턴합니다.

// input
[ -2, 1, -3, 4, -1, 2, 1, -5, 4 ]
// output
6
(4, -1, 2, 1 을 더하면 6이 가장 크기 때문)

풀이

forEach 로 배열 요소를 돌면서 현재값과 누적값을 더합니다. 이때 0보다 큰 값만 누적되도록 0 과 (누적값+현재값) 을 비교해 - 값이 나오는 경우는 누적값을 0으로 할당합니다. 그렇게 구해지는 누적값은 최대값과 비교해서 가장 큰 최대값이 최종적으로 저장되게 합니다.

const nums = [-2,1,-3,4,-1,2,1,-5,4]

const maxSubArray = arr => {
  let max = 0; // 최대값 담을 변수 선언, 초기값 0 할당
  let cur = 0; // 누적값 담을 변수 선언, 초기값 0 할당

  arr.forEach((el)=>{ // forEach 함수로 배열 요소를 돌며
    cur = Math.max(0, cur + el); // 누적값과 0을 비교해
    max = Math.max(max, cur)
  });
  return max;
}

콘솔을 찍어 중간 과정을 확인해보면 아래와 같습니다.

const nums = [-2,1,-3,4,-1,2,1,-5,4]

const maxSubArray = arr => {
  let max = 0;
  let cur = 0;

  arr.forEach((el)=>{
    console.log("el => ", el);
    console.log("before cur => ", cur);
    cur = Math.max(0, cur + el);
    console.log("after cur => " ,cur);
    console.log("before max => ", max);
    max = Math.max(max, cur)
    console.log("after max => ", max);
    console.log("------------------------")
  });
  return max;
}

콜솔 결과값 출력

el =>  -2
before cur =>  0
after cur =>  0
before max =>  0
after max =>  0
------------------------
el =>  1
before cur =>  0
after cur =>  1
before max =>  0
after max =>  1
------------------------
el =>  -3
before cur =>  1
after cur =>  0
before max =>  1
after max =>  1
------------------------
el =>  4
before cur =>  0
after cur =>  4
before max =>  1
after max =>  4
------------------------
el =>  -1
before cur =>  4
after cur =>  3
before max =>  4
after max =>  4
------------------------
el =>  2
before cur =>  3
after cur =>  5
before max =>  4
after max =>  5
------------------------
el =>  1
before cur =>  5
after cur =>  6
before max =>  5
after max =>  6
------------------------
el =>  -5
before cur =>  6
after cur =>  1
before max =>  6
after max =>  6
------------------------
el =>  4
before cur =>  1
after cur =>  5
before max =>  6
after max =>  6
------------------------
정답 =>  6
profile
Today I Learned

0개의 댓글