分治算法
利用分治算法解决问题的三个步骤
1.将原问题分解为一组子问题,没个子问题都与原问题类型相同,但是比原问题的规模小;
2.递归求解这些字问题;
3.将子问题的求解结果恰当合并,得到原问题的解。
简单来说就是:原问题分解(分解)、最小子问题求解(解决)、子问题解得合并(合并).
最大子数组问题
Leetcode(https://leetcode.com)上的121题可转化成这种问题,题目如下:
Say you have an array for which the ith element is the price of a given stock on day i.
If you were only permitted to complete at most one transaction (ie, buy one and sell one share of the stock), design an algorithm to find the maximum profit.
Example 1: Input: [7, 1, 5, 3, 6, 4] Output: 5
max. difference = 6-1 = 5 (not 7-1 = 6, as selling price needs to be larger than buying price)
Example 2: Input: [7, 6, 4, 3, 1] Output: 0
In this case, no transaction is done, i.e. max profit = 0.
本来这题用动态规划做的话会很简单,在这里将它稍微复杂化一下。
我们不单纯考虑某天与某天的价格差,而是考虑每天的价格变化,这样原问题就转化成了求最大子数组问题(即数组里面的元素相加最大)。以Example1为例的价格变化数组A为[-6, 4, -2, 3, -2].
按分治法的思想,将A分为长度基本相同的两部分A1(-6, 4)、A2(-2, 3, -2)(分解);原问题就变成了分别求解A1的最大子数组和A2的最大子数组和跨分点的最大子数组(其中求解A1和A2可以继续递归,问题的重点在于求跨分点的最大子数组);最后比较求出的这三者,取最大者即为所求。
下面为求跨分点的最大子数组的伪代码:
1 left-sum = -oo (oo表示无穷)
2 sum = 0
3 for i = mid downto low
4 sum = sum + A[i]
5 if sum > left-sum
6 left-sum = sum
7 max-left = i
8 right-sum = -oo
9 sum = 0
10 for j = mid + 1 to high
11 sum = sum + A[j]
12 if sum > right-sum
13 right-sum = sum
14 max-right = j
15 return (max-left, max-right, left-sum + right-sum)
16 //其中mid为分割左右数组的位置
比较求最大就不再赘述!持续更新中。。。