[LeetCode] 1299. Replace Elements with Greatest Element on Right Side

Chobby·2025년 8월 5일
1

LeetCode

목록 보기
491/582

😎풀이

  1. resultn의 길이를 갖는 배열 메모리를 할당한다.
  2. 마지막 요소는 반드시 -1이 된다.
  3. 배열의 오른쪽 끝을 기준으로 왼쪽으로 순회한다.
    3-1. 최댓값을 해당 자리에 할당하며 지속적으로 최댓값을 탐색한다.
  4. 변형된 배열을 반환한다.
function replaceElements(arr: number[]): number[] {
    const n = arr.length
    const result = Array(n)
    result[n - 1] = -1
    let max = arr[n - 1]
    for(let i = arr.length - 2; i >= 0; i--) {
        result[i] = max
        max = Math.max(max, arr[i])
    }
    return result
};
profile
내 지식을 공유할 수 있는 대담함

0개의 댓글