[Coding Made Simple] Weighted Job Scheduling

本文介绍了一种基于动态规划的任务调度算法,通过将任务按结束时间升序排列并计算非重叠任务的最大收益,实现任务调度最优化。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Given certain jobs with start and end time and amount you make on finishing the job, find the maximum value you can make by scheduling jobs in non-overlapping way.

 

Dynamic programming solution.

First sort all the jobs in ascending order based on their end time. This makes checking if two jobs overlap or not easier. 

State: maxGain[i]: Given the first i jobs, the max profit we can get by selecting jobs[i]. 

Function: maxGain[i] = max {maxGain[i], maxGain[j] + jobs[i].gain}, for j in [0, i)

Initialization: maxGain[i] = jobs[i].gain, as we know by selecting jobs[i], we at least have a profit of jobs[i].gain.

Answer:  the max value of maxGain[i]. 

 

 1 import java.util.Arrays;
 2 
 3 class Job implements Comparable<Job>{
 4     int start;
 5     int end;
 6     int gain;
 7     Job(int start, int end, int gain) {
 8         this.start = start;
 9         this.end = end;
10         this.gain = gain;
11     }
12     public int compareTo(Job o) {
13         return this.end - o.end;
14     }
15 }
16 public class WeightedJobScheduling {
17     public int getMaxGain(Job[] jobs) {
18         Arrays.sort(jobs);
19         int[] maxGain = new int[jobs.length];
20         for(int i = 0; i < maxGain.length; i++) {
21             maxGain[i] = jobs[i].gain;
22         }
23         for(int i = 1; i < maxGain.length; i++) {
24             for(int j = 0; j < i; j++) {
25                 if(jobs[i].start >= jobs[j].end) {
26                     maxGain[i] = Math.max(maxGain[i], maxGain[j] + jobs[i].gain);
27                 }
28             }
29         }
30         
31         int max = Integer.MIN_VALUE;
32         for(int i = 0; i < maxGain.length; i++) {
33             if(maxGain[i] > max) {
34                 max = maxGain[i];
35             }
36         }
37         return max;
38     }
39 }

 

转载于:https://www.cnblogs.com/lz87/p/7288799.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值