python - Python:如何找到具有连接间隔开始和结束的最长连续间隔
问题描述
如何找到最长连接区间链的长度?
例子:
[-4,1][1,5][2,10][3,5][1,3][3,8][8,12][5,11]
这里最长的链是:
[-4,1][1,3][3,8][8,12]
如您所见,当前间隔的结束应该是下一个间隔的开始。我想从某种意义上找到最长链的长度:length=(12-(-4))=16
我认为这涉及递归?但我不知道如何在 Python 中实现它。
提前致谢
解决方案
动态规划:
from collections import defaultdict
intervals = [-4,1][1,5][2,10][3,5][1,3][3,8][8,12][5,11]
intervals = sorted(intervals, key=lambda x: (x[1], x[0])) # will sort by end, then start
distances = defaultdict(int)
for start, end in intervals:
# this is the key step: at each point, the max length interval up to here
# is max combined length of all intervals that end here
distances[end] = max(distances[end], distances[start] + end-start)
print(max(distances.values()))
推荐阅读
- angular - 即使在 angular 2 项目中成功输出后,我也会收到错误消息。为什么这样?
- php - 更改通知:未定义索引错误为用户友好的“不存在”
- fabricjs - 织物画布文本读取 html 标记
- makefile - Makefile 删除后不重新生成主要目标
- python - Scrapy 爬行
- ruby-on-rails - AWS/Ruby On Rails/Puma/Nginx 最大请求数
- python - numpy 数组的 zip_longest
- outlook-redemption - 是否需要在 Outlook 对象模型中发布 MAPIOBJECT?
- microsoft-edge - 当 Microsoft Chromium Edge 磁贴不接受桌面链接磁贴时,如何向 StartLayout 添加参数?
- templates - 无法在新项目表单上公开现有控件