https://school.programmers.co.kr/learn/courses/30/lessons/118667
문제가 길어 링크로 대체합니다!
import Foundation
func solution(_ queue:[Int], _ queue2:[Int]) -> Int {
var sum = queue.reduce(0) {$0+$1}
var sum2 = queue2.reduce(0) {$0+$1}
var totalSum = sum + sum2
var answer = 0
let one = queue
var queue = queue
var queue2 = queue2
if totalSum % 2 != 0 {
return -1
}
while sum != sum2 {
if sum > sum2 {
queue2.append(queue.removeFirst())
answer += 1
} else {
queue.append(queue2.removeFirst())
answer += 1
}
sum = queue.reduce(0) {$0+$1}
sum2 = queue2.reduce(0) {$0+$1}
if queue == one {
return -1
}
}
return answer
}
완전 탐색식으로 풀었는데 시간 초과가 나더라구요..
import Foundation
func solution(_ queue:[Int], _ queue2:[Int]) -> Int {
var sum = queue.reduce(0) {$0+$1}
var sum2 = queue2.reduce(0) {$0+$1}
var totalSum = sum + sum2
var answer = 0
var left = 0
var right = queue.count
var array = queue + queue2
var goal = (totalSum / 2)
if totalSum % 2 != 0 {
return -1
}
if goal < queue.max()! || goal < queue2.max()! {
return -1
}
while right < array.count && left <= right {
if sum < goal {
sum += array[right]
right += 1
} else if sum > goal {
sum -= array[left]
left += 1
} else {
break
}
answer += 1
}
if sum != goal {
return -1
}
return answer
}