MaxIncomeVO.java:
import java.io.Serializable;
public class MaxIncomeVO implements Serializable {
private Integer maxIncome_holding;
private Integer maxIncome_not_holding;
StockIncomeTest.java:
import com.alibaba.fastjson.JSONObject;
import java.util.ArrayList;
public class StockIncomeTest {
public static void main(String[] args) {
int[] prices = generateRandomPriceList(20,20,1);
System.out.print( "股票价格趋势:" );
System.out.println( JSONObject.toJSONString( prices ) );
MaxIncomeVO maxIncome = calculateMaxIncome(prices);
System.out.println( "最大收益:" + maxIncome.getMaxIncome_not_holding() + " 元" );
private static MaxIncomeVO calculateMaxIncome(int[] prices) {
int size = prices.length;
MaxIncomeVO[] dp = new MaxIncomeVO[ size ];
for( int i=0;i
int price_curr = prices[i];
MaxIncomeVO maxIncome_curr = new MaxIncomeVO();
maxIncome_curr.setMaxIncome_holding( 0 - price_curr );
maxIncome_curr.setMaxIncome_not_holding( 0 );
MaxIncomeVO maxIncome_prev = dp[i - 1];
int maxIncome_holding_1 = 0 - price_curr;
int maxIncome_holding_2 = maxIncome_prev.getMaxIncome_holding();
maxIncome_curr.setMaxIncome_holding( Math.max( maxIncome_holding_1,maxIncome_holding_2 ) );
int maxIncome_not_holding_1 = maxIncome_prev.getMaxIncome_holding() + price_curr;
int maxIncome_not_holding_2 = maxIncome_prev.getMaxIncome_not_holding();
maxIncome_curr.setMaxIncome_not_holding( Math.max( maxIncome_not_holding_1,maxIncome_not_holding_2 ) );
dp[ i ] = maxIncome_curr;
private static int[] generateRandomPriceList(int size,int maxValue,int minValue) {
int[] prices = new int[size];
Random random = new Random();
int range = maxValue - minValue;
for (int i = 0; i < size; i++) {
prices[ i ] = random.nextInt( range ) + minValue;