Skip to content

Commit 35c937c

Browse files
author
Yi Gu
committed
Add a new solution to the Maximum Profit in Job Scheduling
1 parent d3f143a commit 35c937c

File tree

1 file changed

+73
-0
lines changed

1 file changed

+73
-0
lines changed

DP/MaximumProfitJobScheduling.swift

Lines changed: 73 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,73 @@
1+
/**
2+
* Question Link: https://leetcode.com/problems/maximum-profit-in-job-scheduling/
3+
* Primary idea: Dynamic Programming, dp[i] means the max profit starting at i, find valid next job using binary search.
4+
* Time Complexity: O(nlogn), Space Complexity: O(n)
5+
*/
6+
7+
class MaximumProfitJobScheduling {
8+
func jobScheduling(_ startTime: [Int], _ endTime: [Int], _ profit: [Int]) -> Int {
9+
let jobs = constructJobs(startTime, endTime, profit)
10+
var maxProfits = Array(repeating: -1, count: jobs.count), maxProfit = Int.min
11+
12+
for i in 0..<jobs.count {
13+
maxProfit = max(findMaxProfit(jobs, i, &maxProfits), maxProfit)
14+
}
15+
16+
return maxProfit
17+
}
18+
19+
private func findMaxProfit(_ jobs: [Job], _ index: Int, _ maxProfits: inout [Int]) -> Int {
20+
if index == jobs.count {
21+
return 0
22+
}
23+
24+
if maxProfits[index] != -1 {
25+
return maxProfits[index]
26+
}
27+
28+
let nextIndex = findNextIndex(jobs, index)
29+
30+
let maxProfit = max(findMaxProfit(jobs, index + 1, &maxProfits), jobs[index].profit + findMaxProfit(jobs, nextIndex, &maxProfits))
31+
32+
maxProfits[index] = maxProfit
33+
34+
return maxProfit
35+
}
36+
37+
private func findNextIndex(_ jobs: [Job], _ index: Int) -> Int {
38+
var left = index, right = jobs.count - 1
39+
var mid = 0
40+
41+
while left <= right {
42+
mid = (right - left) / 2 + left
43+
44+
// overlap
45+
if jobs[index].endTime <= jobs[mid].startTime {
46+
right = mid - 1
47+
} else {
48+
left = mid + 1
49+
}
50+
}
51+
52+
return right + 1
53+
}
54+
55+
56+
private func constructJobs(_ startTime: [Int], _ endTime: [Int], _ profit: [Int]) -> [Job] {
57+
return (0..<startTime.count)
58+
.map { Job(startTime: startTime[$0], endTime: endTime[$0], profit: profit[$0]) }
59+
.sorted {
60+
if $0.startTime != $1.startTime {
61+
return $0.startTime < $1.startTime
62+
} else {
63+
return $0.endTime < $1.endTime
64+
}
65+
}
66+
}
67+
68+
struct Job {
69+
var startTime: Int
70+
var endTime: Int
71+
var profit: Int
72+
}
73+
}

0 commit comments

Comments
 (0)