[백준 1744] 수 묶기

Junyoung Park·2022년 5월 1일
0

코딩테스트

목록 보기
407/631
post-thumbnail

1. 문제 설명

수 묶기

2. 문제 분석

정렬 후 두 개씩 수를 곱할 수 있을 때, 가장 값이 큰 결과를 얻기 위해서는 (양/음 모두) 수의 차이가 가장 작은 두 수를 곱한 값을 더하는 것이다. 이때 예외는 양수 1을 곱했을 때에는 값이 같기 때문에 1은 덧셈으로, 음수 두 개를 곱할 수 없을 때에는 0을 통해 없애주거나 최소화해야 한다는 점이다.

3. 나의 풀이

import Foundation

let N = Int(String(readLine()!))!
var positive = [Int]()
var zeros = [Int]()
var negative = [Int]()
for _ in 0..<N{
    let num = Int(String(readLine()!))!
    if num > 0{
        positive.append(num)
    } else if num == 0{
        zeros.append(num)
    } else{
        negative.append(num)
    }
}

var total = 0

positive.sort(by: <)

while true{
    if positive.isEmpty == false && positive[0] == 1{
        total += positive.removeFirst()
    } else{
        break
    }
}

if positive.count % 2 == 1{
    total += positive.removeFirst()
}

var cursor = 0
for _ in 0..<positive.count/2{
    let times = positive[cursor] * positive[cursor+1]
    total += times
    cursor += 2
}

negative.sort(by: >)
if negative.count % 2 == 1 && zeros.count > 1{
    negative.removeFirst()
} else if negative.count % 2 == 1 && zeros.count < 1{
    total += negative.removeFirst()
}

cursor = 0
for _ in 0..<negative.count/2{
    let times = negative[cursor] * negative[cursor+1]
    total += times
    cursor += 2
}

print(total)
profile
JUST DO IT

0개의 댓글