๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
๐Ÿ Algorithm/์•Œ๊ณ ๋ฆฌ์ฆ˜-Swift

[99ํด๋Ÿฝ ์ฝ”ํ…Œ ์Šคํ„ฐ๋”” 5์ผ์ฐจ TIL] ๋ฐฑ์ค€ ์ˆ˜์—ด Swift

by Danna 2025. 4. 5.
728x90
728x90

 

์˜ค๋Š˜์˜ ๋ฌธ์ œ

- ๋ฐฑ์ค€ ์ˆ˜์—ด

- https://www.acmicpc.net/problem/2559

 

์˜ค๋Š˜์˜ ํ•™์Šต ํ‚ค์›Œ๋“œ

- N ์˜ ํฌ๊ธฐ์™€ ์‹œ๊ฐ„ ๋ณต์žก๋„

- ํˆฌ ํฌ์ธํ„ฐ

 

์ ‘๊ทผ ๋ฐฉ๋ฒ•

N ์˜ ํฌ๊ธฐ์™€ ์‹œ๊ฐ„ ๋ณต์žก๋„

- ์ž…๋ ฅ์ด 2 <= N <= 100,000 ์ด๊ณ  1 <= K <= N ์ด๋‹ค.

- ๋‹จ์ˆœํ•˜๊ฒŒ 2์ฐจ์› ๋ฐ˜๋ณต๋ฌธ์œผ๋กœ ๋ฐฐ์—ด์—์„œ ์—ฐ์†์ ์ธ ํ•ฉ์„ ๊ตฌํ•˜๊ฒŒ ๋˜๋ฉด

- ์ตœ๋Œ€ ์‹œ๊ฐ„ ๋ณต์žก๋„๋Š” N * N = 00,000,000,000 ์ด ๋  ์ˆ˜ ๋„ ์žˆ๋‹ค. 

 

ํˆฌ ํฌ์ธํ„ฐ

- ๋ฒ”์œ„๋ฅผ ์ง€์ •ํ•ด์„œ ์ „์ฒด ํ•ฉ์„ ๊ตฌํ•ด์•ผ ํ•˜๋Š”๋ฐ, 2์ฐจ์› ๋ฐ˜๋ณต๋ฌธ์œผ๋กœ ๊ณ„์‚ฐํ•˜๊ธฐ์—๋Š” ์‹œ๊ฐ„ ๋ณต์žก๋„๊ฐ€ ํฌ๊ธฐ์— ๋‹ค๋ฅธ ๋ฐฉ์‹์„ ์ฐพ์•„์•ผ ํ–ˆ๋‹ค.

- ์‹œ์ž‘, ๋ ์ง€์ ์„ ๊ณ„์‚ฐํ•ด๋†“๊ณ , ์ˆœ์„œ๋Œ€๋กœ ์ธ๋ฑ์Šค๋ฅผ ์ฆ๊ฐ€์‹œํ‚ค๋ฉด์„œ ๊ณ„์‚ฐํ•˜๋ฉด ์‹œ๊ฐ„ ๋ณต์žก๋„๊ฐ€ ์ค„์–ด๋“ค ์ˆ˜ ์žˆ๋‹ค.

 

๋ฌธ์ œ ํ’€์ด

// ๋งค์ผ 9์‹œ ํ•™๊ต์—์„œ ์ธก์ •ํ•œ ์˜จ๋„
// 3 -2 -4 -9 0 3 7 13 8 -3
// ์—ฐ์†์ ์ธ ๋ฉฐ์น  ๋™์•ˆ์˜ ์˜จ๋„์˜ ํ•ฉ์ด ๊ฐ€์žฅ ํฐ ๊ฐ’์€?
// 5์ผ ๊ฐ„์˜ ์˜จ๋„์˜ ํ•ฉ = [-12, -12, -3, 14, 31, 28]
// ๊ฐ€์žฅ ํฐ ์˜จ๋„์˜ ํ•ฉ = 31

// N : ์˜จ๋„๋ฅผ ์ธก์ •ํ•œ ์ „์ฒด ๋‚ ์งœ์˜ ์ˆ˜, 2 <= N <= 100,000 (์ตœ๋Œ€ ๋ฐ˜๋ณต์€? N * N = 100,000,000,000)
// K : ํ•ฉ์„ ๊ตฌํ•˜๊ธฐ ์œ„ํ•œ ์—ฐ์†์ ์ธ ๋‚ ์งœ์˜ ์ˆ˜, 1 <= K <= N

func findMaxTempSum(_ n: Int, _ k: Int, _ tempArray: [Int]) -> Int {
    var start = 0
    var end = k
    var sum = tempArray[start..<end].reduce(0, +)
    var maxSum = sum

    for _ in 1..<n {
        guard end < n else {
            break
        }

        start += 1
        end += 1

        sum = sum - tempArray[start - 1] + tempArray[end - 1]
        maxSum = max(maxSum, sum)
    }

    return maxSum
}

func readInput() -> (Int, Int, [Int])? {
    guard let input = readLine() else {
        return nil
    }

    let splitedInput = input.split(separator: " ")
    guard let n = Int(splitedInput[0]), let k = Int(splitedInput[1]) else {
        return nil
    }

    let inputArray = readLine()?.split(separator: " ").compactMap { Int($0) } ?? []
    return (n, k, inputArray)
}

if let (n, k, tempArray) = readInput() {
    let result = findMaxTempSum(n, k, tempArray)
    print(result)
}

 

- ์ดˆ๊ธฐ ์ฝ”๋“œ์—์„œ๋Š” guard ๊ตฌ๋ฌธ ์ด์ „์— start, end ์ธ๋ฑ์Šค๋ฅผ +1 ํ•ด์คฌ์–ด์„œ ๋งˆ์ง€๋ง‰ ๊ฐ’ ๊ณ ๋ ค๊ฐ€ ์–ด๋ ค์› ๋‹ค.

- ํ…Œ์ŠคํŠธ ์ผ€์ด์Šค๋ฅผ ์•„๋ž˜์ฒ˜๋Ÿผ ํ–ˆ์„๋•Œ, 7์ด ๋‚˜์™€์•ผํ•˜๋Š”๋ฐ 5๊ฐ€ ๋‚˜์™”์—ˆ๋‹ค.

4 2

1 2 3 4

- ์œ„์˜ ํ…Œ์ŠคํŠธ ์ผ€์ด์Šค๋ฅผ ํ†ตํ•ด ๋งˆ์ง€๋ง‰ ์ธ๋ฑ์Šค๊ฐ€ ์ž˜๋ชป ๊ณ„์‚ฐ๋œ๊ฒƒ์„ ์•Œ๊ฒŒ ๋˜์—ˆ๋‹ค.

 

์˜ค๋Š˜์˜ ํšŒ๊ณ 

- ์ž…๋ ฅ์˜ ํฌ๊ธฐ์™€ ๊ตฌํ˜„ ๋ฐฉ์‹์— ๋”ฐ๋ผ ์‹œ๊ฐ„ ๋ณต์žก๋„๋ฅผ ์ƒ๊ฐํ•ด๋ณด์ž.

- ์˜ˆ์™ธ ์ผ€์ด์Šค๋ฅผ ๊ณ ๋ คํ•ด๋ณด์ž.

 

728x90
728x90