题目是给你一堆24小时内旅店预定的信息,{{"2-4", "100"}, {"4-8", "200"}, {"5-7", "300"}},要求找出收入最大的un-overlapping的时间段。
这题需要clarify一下如果两个时间段overlap了怎么办? 是两都不算呢,还是merge在一起, 还有怎么算 overlap, 100-200, 200-300算overlap吗
下面的解法是按需要merge做的。如果不能merge的话随便改一下就好了。
public class MaxProfitInterval {
/*
题目是给你一堆24小时内旅店预定的信息,{{"2-4", "100"}, {"4-8", "200"}, {"5-7", "300"}},要求找出收入最大的un-overlapping的时间段。
*/
public int[] maxProfitInterval(List<String[]> info) {
//process intervals
List<Interval> intervals = processInput(info);
//sort intervals
Collections.sort(intervals, new Comparator<Interval>() {
@Override
public int compare(Interval o1, Interval o2) {
return o1.start - o2.start;
}
});
//merge intervals
Interval holder = null;
int maxProfit = 0;
int[] ans = null;
for (Interval itv : intervals) {
if (holder == null) {
holder = itv;
} else if (itv.start <= holder.end) {
holder.end = Math.max(holder.end, itv.end);
holder.profit += itv.profit;
} else {
if (holder.profit > maxProfit) {
ans = new int[]{holder.start, holder.end};
maxProfit = holder.profit;
}
holder = itv;
}
}
if (holder != null && holder.profit > maxProfit) {
ans = new int[]{holder.start, holder.end};
maxProfit = holder.profit;
}
//Display.myPrint(ans);
//Display.myPrint(maxProfit);
return ans;
}
private List<Interval> processInput(List<String[]> info) {
List<Interval> ans = new ArrayList<>();
for (String[] record : info) {
String[] time = record[0].split("-");
int profit = Integer.parseInt(record[1]);
ans.add(new Interval(Integer.parseInt(time[0]),
Integer.parseInt(time[1]), profit));
}
return ans;
}
class Interval {
int start, end;
int profit;
public Interval(int start, int end, int profit) {
this.start = start;
this.end = end;
this.profit = profit;
}
}
public static void main(String[] args) {
MaxProfitInterval solution = new MaxProfitInterval();
List<String[]> info = new ArrayList<>();
info.add(new String[]{"2-3", "100"});
info.add(new String[]{"4-8", "200"});
info.add(new String[]{"5-7", "300"});
solution.maxProfitInterval(info);
}
}
网友评论