HIT해
[Swift/프로그래머스] 수식 최대화 ( 그리디 , 연산 ) 본문
728x90
https://school.programmers.co.kr/learn/courses/30/lessons/67257
프로그래머스
SW개발자를 위한 평가, 교육, 채용까지 Total Solution을 제공하는 개발자 성장을 위한 베이스캠프
programmers.co.kr
빡구현 문제다.
이런 양의 구현요구를 하면 이게 정답으로 처리가 될까? 확신하지 않으면 불안할거같다..
import Foundation
import Foundation
func solution(_ expression:String) -> Int64 {
var oper = ["+","-","*"]
var oop = [[String]]()
// 조합의 경우의 수
func combi(_ targetArr : [String], _ arr:[String]) {
if arr.count == 3 {
oop.append(arr)
return
}
for i in 0...2{
if !arr.contains(oper[i]){
combi(targetArr, arr + [targetArr[i]])
}
}
}
combi(oper,[])
// 수식 분리하기
var numbers: [Int64] = []
var operators: [String] = []
var currentNum = ""
for char in expression {
if char.isNumber {
currentNum += String(char)
} else {
if !currentNum.isEmpty {
numbers.append(Int64(currentNum)!)
currentNum = ""
}
operators.append(String(char))
}
}
// 마지막 숫자 처리
if !currentNum.isEmpty {
numbers.append(Int64(currentNum)!)
}
// 각 우선순위 조합에 대해 계산
var maxResult: Int64 = 0
for priority in oop {
var tempNumbers = numbers
var tempOperators = operators
// 우선순위대로 계산
for op in priority {
var i = 0
while i < tempOperators.count {
if tempOperators[i] == op {
let num1 = tempNumbers[i]
let num2 = tempNumbers[i + 1]
let result: Int64
switch op {
case "+":
result = num1 + num2
case "-":
result = num1 - num2
case "*":
result = num1 * num2
default:
result = 0
}
tempNumbers[i] = result
tempNumbers.remove(at: i + 1)
tempOperators.remove(at: i)
i -= 1
}
i += 1
}
}
maxResult = max(maxResult, abs(tempNumbers[0]))
}
return maxResult
}
누적합은 배열의 값을 변경하고 줄이는 과정에서 진행했다.
tempNumbers[i] = result
tempNumbers.remove(at: i + 1)
tempOperators.remove(at: i)
i -= 1
tempNumbers = [5, 6, 2, 3]
tempOperators = ["*", "+", "*"]
5 * 6 = 30
tempNumbers = [30, 2, 3]
tempOperators = ["+", "*"]
2 * 3 = 6
tempNumbers = [30, 6]
tempOperators = ["+"]
30 + 6 = 36
tempNumbers = [36]
tempOperators = []
'Swift > 알고리즘' 카테고리의 다른 글
[Swift/프로그래머스] 카펫 ( 완전탐색 ) (0) | 2024.11.02 |
---|---|
[Swift/프로그래머스] 가장 먼 노드 ( 그래프 , BFS ) (0) | 2024.11.02 |
[Swift] 순열 (0) | 2024.11.02 |
[Swift] 조합 (0) | 2024.11.02 |
[Swift/프로그래머스] N으로 표현 ( 그리디 , 연산 ) (0) | 2024.11.01 |