Bibi's DevLog ๐Ÿค“๐ŸŽ

[๋ฐฑ์ค€ 2846] ์˜ค๋ฅด๋ง‰๊ธธ (Swift) ๋ณธ๋ฌธ

ํ”„๋กœ๊ทธ๋ž˜๋ฐ/์•Œ๊ณ ๋ฆฌ์ฆ˜ ํ’€์ด Swift

[๋ฐฑ์ค€ 2846] ์˜ค๋ฅด๋ง‰๊ธธ (Swift)

๋น„๋น„ bibi 2022. 9. 23. 15:25

2846๋ฒˆ: ์˜ค๋ฅด๋ง‰๊ธธ

  • ๋’ค์˜ ์ˆ˜๊ฐ€ ์•ž์˜ ์ˆ˜๋ณด๋‹ค ํด ๋•Œ๋งŒ ์˜ค๋ฅด๋ง‰๊ธธ์ด๋ผ๊ณ  ํŒ๋‹จํ•œ๋‹ค.

ํ’€์ด1

๋‚˜๋Š” ์˜ค๋ฅด๋ง‰๊ธธ์ธ ๋ฐฐ์—ด์„ ๋งค๋ฒˆ ๋ฐ›์•„์„œ ๊ทธ ์ตœ์†Ÿ๊ฐ’๊ณผ ์ตœ๋Œ“๊ฐ’์„ ํŒ๋‹จํ–ˆ๋‹ค.

let count = Int(readLine()!)!
let inputArr = readLine()!.split(separator: " ").map { Int($0)! }
var previousValue = 0
var uphill: [Int] = []
var maxUphillHeight = 0
for index in inputArr.indices {
    let input = inputArr[index]
    if previousValue != 0 {
        if input - previousValue > 0 { // ์˜ค๋ฅด๋ง‰
            if uphill.isEmpty {
                uphill.append(previousValue)
            }
            uphill.append(input)
        }
        if input - previousValue <= 0 
                        || index == (inputArr.indices.endIndex - 1) { // ์˜ค๋ฅด๋ง‰์ด ์•„๋‹ˆ๊ฑฐ๋‚˜, ์ž…๋ ฅ์˜ ๋์ธ ๊ฒฝ์šฐ
            if !uphill.isEmpty {
                let uphillHeight = uphill.max()! - uphill.min()!
                if uphillHeight > maxUphillHeight {
                    maxUphillHeight = uphillHeight
                }
                uphill = []
            }
        }
    }
    previousValue = input
}
print(maxUphillHeight)

๊ทธ๋Ÿฐ๋ฐ ๋‹ค๋ฅธ ํ’€์ด๋ฅผ ๋ณด๋‹ˆ ๋‚˜๋ณด๋‹ค ํ›จ์”ฌ ์ฝ”๋“œ๊ฐ€ ๊ฐ„๊ฒฐํ–ˆ๋‹ค.

์˜ค๋ฅด๋ง‰๊ธธ์ž„์ด ํŒ๋ช…๋˜๋ฉด (๋’ค์˜ ์ˆ˜ > ์•ž์˜ ์ˆ˜) ์˜ค๋ฅด๋ง‰๊ธธ์ธ ๊ตฌ๊ฐ„์˜ ์ตœ๋Œ“๊ฐ’๊ณผ ์ตœ์†Ÿ๊ฐ’์„ ๊ตฌํ•  ํ•„์š”๊ฐ€ ์—†๋‹ค.

์˜ค๋ฅด๋ง‰๊ธธ์ž„์ธ ์ด์ƒ ๋ฌด์กฐ๊ฑด ์•ž์˜ ์ˆ˜๋ณด๋‹ค ๋’ค์˜ ์ˆ˜๊ฐ€ ํด ๊ฒƒ์ด๊ณ , ์ตœ์†Ÿ๊ฐ’์€ ๋ฐ˜๋“œ์‹œ ๋งจ ์•ž์˜ ์ˆ˜, ์ตœ๋Œ“๊ฐ’์€ ๋ฐ˜๋“œ์‹œ ๋งจ ๋’ค์˜ ์ˆ˜๊ฐ€ ๋œ๋‹ค.

๋”ฐ๋ผ์„œ ์˜ค๋ฅด๋ง‰๊ธธ์˜ ์‹œ์ž‘์ ๊ณผ ๋์ ๋งŒ ํŒ๋‹จํ•˜๋ฉด ๋” ๊ฐ„๋‹จํ•˜๊ฒŒ ์ฝ”๋“œ๋ฅผ ์งค ์ˆ˜ ์žˆ๋Š” ๊ฑฐ์˜€๋‹ค!

ํ’€์ด2

  • ์ถœ์ฒ˜ https://my-coding-notes.tistory.com/364
  • ์˜ค๋ฅด๋ง‰์˜ ์‹œ์ž‘์ ๊ณผ ๋์ ๋งŒ ํŒ๋ณ„ํ•˜๋‹ˆ ์ฝ”๋“œ ์–‘์„ ๋‘๋ฐฐ ๊ฐ€๊นŒ์ด ์ค„์ผ ์ˆ˜ ์žˆ๊ฒŒ ๋˜์—ˆ๋‹ค.
let count = Int(readLine()!)!
let inputArr = readLine()!.split(separator: " ").map { Int($0) }
var uphillStart = inputArr[0]!
var uphillEnd = inputArr[0]!
var answer = 0
for i in 1..<count {
    if inputArr[i]! <= uphillEnd {
        uphillStart = inputArr[i]!
        uphillEnd = inputArr[i]!
    } else {
        uphillEnd = inputArr[i]!
    }
    answer = max(answer, uphillEnd - uphillStart)
}
print(answer)