Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
47 changes: 47 additions & 0 deletions Sources/DynamicProgramming/RodCuttingMaxProfit.swift
Original file line number Diff line number Diff line change
@@ -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..<bestProfit.count {
var maximumProfit = priceArray[rodLength]

for potentialCut in stride(from: rodLength, through: 1, by: -1) {
let remainingRodLength = rodLength - potentialCut
let remainingRodBestPrice = bestProfit[remainingRodLength]
let totalProfitWithCutAndRemainingBest = remainingRodBestPrice + priceArray[potentialCut]

if totalProfitWithCutAndRemainingBest > maximumProfit {
maximumProfit = totalProfitWithCutAndRemainingBest
}
}
bestProfit[rodLength] = maximumProfit
}

return bestProfit[prices.count]
}
}
Original file line number Diff line number Diff line change
@@ -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)
}
}
}