diff --git a/Sources/DynamicProgramming/RodCuttingMaxProfit.swift b/Sources/DynamicProgramming/RodCuttingMaxProfit.swift new file mode 100644 index 0000000..2f22c3f --- /dev/null +++ b/Sources/DynamicProgramming/RodCuttingMaxProfit.swift @@ -0,0 +1,47 @@ +// +// RodCuttingMaxProfit.swift +// SwiftyAlgorithms +// +// Created by Mohshinsha Shahmadar on 2025-04-23. +// + +import Foundation + +/** + Given a rod of length n and an array of prices that contains prices of all pieces of size smaller than n. + Determine the maximum profit obtainable by cutting up the rod and selling the pieces. + + Sample inputs and outputs: + Input: [1, 5, 8, 9, 10, 17, 17, 20] + Output: 22 + */ +func rodCuttingMaxProfit(_ prices: [Int]) -> Int { + if prices.isEmpty { + return 0 + } else if prices.count == 1 { + return prices[0] + } else { + let priceArray = [0] + prices + var bestProfit = Array.init(repeating: 0, count: priceArray.count) + + bestProfit[0] = 0 + bestProfit[1] = priceArray[1] + + for rodLength in 2.. maximumProfit { + maximumProfit = totalProfitWithCutAndRemainingBest + } + } + bestProfit[rodLength] = maximumProfit + } + + return bestProfit[prices.count] + } +} diff --git a/Tests/SwiftyAlgorithmsTests/ClimbStairsTests.swift b/Tests/SwiftyAlgorithmsTests/DynamicProgramming/ClimbStairsTests.swift similarity index 100% rename from Tests/SwiftyAlgorithmsTests/ClimbStairsTests.swift rename to Tests/SwiftyAlgorithmsTests/DynamicProgramming/ClimbStairsTests.swift diff --git a/Tests/SwiftyAlgorithmsTests/DynamicProgramming/RodCuttingMaxProfitTests.swift b/Tests/SwiftyAlgorithmsTests/DynamicProgramming/RodCuttingMaxProfitTests.swift new file mode 100644 index 0000000..ed36fc2 --- /dev/null +++ b/Tests/SwiftyAlgorithmsTests/DynamicProgramming/RodCuttingMaxProfitTests.swift @@ -0,0 +1,23 @@ +// +// RodCuttingMaxProfitTests.swift +// SwiftyAlgorithms +// +// Created by Mohshinsha Shahmadar on 2025-04-24. +// + +import XCTest +@testable import SwiftyAlgorithms + +final class RodCuttingMaxProfitTests: XCTestCase { + func testRodCuttingMaxProfit() throws { + let inputs: [AlgorithmTestCase] = [ + .init([], 0), + .init([5], 5), + .init([1, 5, 8, 9, 10, 17, 17, 20], 22) + ] + + testAlgorithm(name: "RodCutting - MaxProfit", with: inputs) { + rodCuttingMaxProfit($0) + } + } +}