题目描述
风口之下,猪都能飞。当今中国股市牛市,真可谓“错过等七年”。 给你一个回顾历史的机会,已知一支股票连续n天的价格走势,以长度为n的整数数组表示,数组中第i个元素(prices[i])代表该股票第i天的股价。 假设你一开始没有股票,但有至多两次买入1股而后卖出1股的机会,并且买入前一定要先保证手上没有股票。若两次交易机会都放弃,收益为0。 设计算法,计算你能获得的最大收益。 输入数值范围:2<=n<=100,0<=prices[i]<=100
输入例子:
3,8,5,1,7,8
输出例子:
12
/**
* 买股票之前不能拥有股票
* 以卖股票为分界点,求两个区间最大数与最小数差的和最大值.
* price[0...i] price[i...n-1]
* Created by ustc-lezg on 16/4/8.
*/
public class Solution {
public int calculateMax(int[] prices) {
int len = prices.length;
int[] lprofit = new int[len];
int[] rprofit = new int[len];
int mprofit = ;
int minprice = prices[];
lprofit[] = ;
int temp;
//从左往右求price[0...i]最大受益
for (int i = ; i < len; i++) {
if (prices[i] < minprice) {
minprice = prices[i];
}
if ((temp = prices[i] - minprice) > mprofit) {
mprofit = temp;
}
lprofit[i] = mprofit;
}
mprofit = ;
rprofit[len - ] = ;
int maxprice = prices[len - ];
//从右往左求price[n-1...i]最大受益
for (int j = len - ; j >= ; --j) {
if (maxprice < prices[j]) {
maxprice = prices[j];
}
if (mprofit < (temp = maxprice - prices[j])) {
mprofit = temp;
}
rprofit[j] = mprofit;
}
mprofit = ;
for (int k = ; k < len; ++k) {
if ((temp = lprofit[k] + rprofit[k]) > mprofit) {
mprofit = temp;
}
}
return mprofit;
}
}