https://school.programmers.co.kr/learn/courses/30/lessons/154539
가장 가까운 최댓값을 찾는 과정
func solution(_ numbers:[Int]) -> [Int] {
var ans = [-1]
var stack = [numbers.last!]
for i in stride(from: numbers.count-2, to: -1, by: -1) {
while !stack.isEmpty && stack.last! <= numbers[i] {
stack.removeLast()
}
if stack.isEmpty {
ans.append(-1)
}
else {
ans.append(stack.last!)
}
stack.append(numbers[i])
}
return ans.reversed()
}
func solution(_ numbers:[Int]) -> [Int] {
var ans = [Int](repeating: -1, count: numbers.count)
var stack = [numbers.last!]
for i in stride(from: numbers.count-2, to: -1, by: -1) {
while !stack.isEmpty && stack.last! <= numbers[i] {
stack.removeLast()
}
if !stack.isEmpty {
ans[i] = stack.last!
}
stack.append(numbers[i])
}
return ans
}
3. Python 풀이
def solution(numbers):
answer = [-1] * len(numbers)
stack = [numbers[-1]]
for i in range(len(numbers)-2, -1, -1):
while len(stack) > 0 and stack[-1] <= numbers[i]:
del stack[-1]
if len(stack) != 0:
answer[i] = stack[-1]
stack.append(numbers[i])
return answer
[프로그래머스] 스킬트리 (1) | 2024.01.08 |
---|---|
[프로그래머스] 땅따먹기 (1) | 2024.01.04 |
[프로그래머스] 단어 변환 (0) | 2024.01.02 |
[프로그래머스] 주차 요금 계산 (0) | 2023.12.29 |
[프로그래머스] 압축 (0) | 2023.12.26 |