1.不限交易次数的情况:对价格序列进行过滤,并将理想的交易点存储在LinkedList中,最后累加头两个相减的值。
private static BigDecimal maxProfit(String[] arr) {
LinkedList<BigDecimal> list = new LinkedList<BigDecimal>();
int i = -1;
while (++i < arr.length) {
BigDecimal curr = new BigDecimal( arr[i] );
if (list.size() == 0) {
list.add( curr );
} else if (list.size() == 1) {
Serializable placeHolder = list.get( 0 ).compareTo( curr ) >= 0 ? list.set( 0, curr ) : list.add( curr );
} else if (i == arr.length - 1) {
if(list.size() % 2 != 0 && curr.compareTo(list.getLast())>0)
list.add( curr );
} else {
BigDecimal next = new BigDecimal( arr[i + 1] );
if ((curr.compareTo( list.getLast() ) < 0 && curr.compareTo( next ) < 0) || (curr.compareTo( list.getLast() ) > 0 && curr.compareTo( next ) > 0))
list.add( curr );
}
}
System.out.println(list);
BigDecimal result = BigDecimal.ZERO;
while (list.size() >= 2) {
result= result.subtract( list.removeFirst().subtract( list.removeFirst() ) );
}
return result;
}
public static void main(String[] args) {
System.out.println( maxProfit( new String[]{"2", "2.1", "1.9", "2.0", "2.4", "2.3", "2.2", "2.1", "2.2", "2.3"} ) );
}
2.若交易限K次,则可使用动态规划矩阵来计算
如输入为: 10,22,5,75,65,80
动态规划矩阵为Profit(i,j):
____________________
|0 12 -5 65 55 70|
|0 0 -17 53 43 58| 步骤一:求最大值的节点
|0 0 0 70 60 75|-----max=Profit(2,5) //第三个点买入,第六个点卖出
|0 0 0 0 -10 5|
|0 0 0 0 0 15|
|0 0 0 0 0 0|
|____________________|
____________________
|0 12 -5 65 55 70|
|0 0 -17 53 43 58| 步骤二:求三、四、五、六点外的,其它点的最大值的节点
|0 0 0 70 60 75|-----max=Profit(0,1) //第一个点买入,第二个点卖出
|0 0 0 0 -10 5|
|0 0 0 0 0 15|
|0 0 0 0 0 0|
|____________________|
...
____________________
|0 12 -5 65 55 70|
|0 0 -17 53 43 58| 步骤K:求第K个最大值的节点
|0 0 0 70 60 75|-----
|0 0 0 0 -10 5|
|0 0 0 0 0 15|
|0 0 0 0 0 0|
|____________________|