原理
将整体问题划分为多个子问题,对每个子问题求解局部最优解,从而推出全局最优解。
例子1
有三个孩子,他们的饥饿程度分别为3,5,6;
现在有五块饼干,大小分别为4,3,2,1,5;
每个孩子只有吃一块大于等于自己饥饿度的饼干,才可以吃饱。
请问:以上最多可以让几个孩子吃饱?
解析:子问题尽量令每个孩子吃一块最小饼干且保证吃饱,这样饥饿程度大的孩子才有可能会吃饱。
Python实现
def eat_bg(child,bg):
child = child #三个孩子的饥饿度
bg = bg # 饼干大小
#只要饼干>=饥饿度,即可吃饱
#对饼干列表排序
bg.sort()
count = 0
i,j = 0,0
while i < len(child) and j < len(bg):
if bg[j] >= child[i]:
i += 1
j += 1
print("%d 个孩子吃饱"%i)
if __name__ == "__main__":
#child = [3,5,6] #三个孩子的饥饿度
#bg = [4,3,2,1,5] # 饼干大小
child =[int(i) for i in input("输入孩子的饥饿度,以逗号分割:").strip().split(",")]
bg = [int(i) for i in input("输入饼干的大小,以逗号分割:").strip().split(",")]
eat_bg(child,bg)
Java实现 pending
例子2
在一个数组中,有很多的区间数组,如[[1,4],[2,5],[5,9]]。试统计有区间重叠的数组个数。
"""
如[[1,4],[2,5],[5,9]]
统计区间重复的数组 的个数
解析:首先按照内部每个数组的最后以为进行升序排序
然后比较前一个数组的末尾与后一个数组的开头,
former > latter 则表示有重叠
"""
def count_over_array(alist):
#按照每个数组的末尾元素排序
alist.sort(key=lambda i:i[1])
print(alist)
count = 0
i = 0
while i < len(alist) - 1:
if alist[i][1] > alist[i+1][0]:
count += 1
i += 1
return count
if __name__ == "__main__":
alist = eval(input("输入你的数组:").strip())
r = count_over_array(alist)
print("重叠的数组个数:",r)
例子3
第i天的股票的价格为 v i v_i vi,如[7,1,5,3,8,4],针对一个给定的数组,计算通过多次的买入、卖出,可以获取的最大收益。
"""
第i天的股票的价格为v_i
如[7,1,5,3,8,4],针对一个给定的数组,计算通过多次的买入、卖出,
可以获取的最大收益。
"""
def judge_stock(alist):
profit = 0
buy_point = []
i = 0
while i < len(alist) - 1:
if alist[i] < alist[i+1]:
buy_point.append(i)
profit += alist[i+1] - alist[i]
i += 1
return buy_point,profit
if __name__ == "__main__":
alist = eval(input("输入你的数组:").strip())
buy, profit = judge_stock(alist)
print("买入股票的点:", buy)
print("可以获得的最大收益:", profit)