Codility Lesson9. Maximum slice problem - MaxProfit

세나정·2023년 4월 26일
0
post-thumbnail

Tasks

https://app.codility.com/programmers/lessons/9-maximum_slice_problem/max_profit/

내 풀이

function solution(A) {
    let maxProfit = 0;
    // 바로 if문에 걸려서 실행될 수 있도록
    let minPrice = Number.MAX_SAFE_INTEGER;

    for (let i = 0; i < A.length; i++) {
        // A[0]값부터 minPrice에 저장하여 다음 인덱스가 더 작을 때 순차적 min 업데이트
        if (A[i] < minPrice) {
            minPrice = A[i];
        }
        // 현재 가격에서 최소 가격을 뺀 값이 최대 이익보다 크면 최대 이익을 갱신
        // 현재가격에서 min을 뺐을 때가 최대 이익보다 크다면 최대이익 갱신
        else if (A[i] - minPrice > maxProfit) {
            maxProfit = A[i] - minPrice;
        }
    }

    return maxProfit;
}

0번 인덱스부터 minPrice에 넣고
다음부터 들어오는 애들이 minPrice보다 크다면 그 값에서 min을 빼주며
최대 이익을 계산함

profile
기록, 꺼내 쓸 수 있는 즐거움

0개의 댓글