您的位置:首页 > 其它

小米笔试题 风口的猪-中国牛市

2016-04-08 20:10 387 查看
题目描述

风口之下,猪都能飞。当今中国股市牛市,真可谓“错过等七年”。 给你一个回顾历史的机会,已知一支股票连续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 = 0;
int minprice = prices[0];
lprofit[0] = 0;
int temp;
//从左往右求price[0...i]最大受益
for (int i = 1; i < len; i++) {
if (prices[i] < minprice) {
minprice = prices[i];
}
if ((temp = prices[i] - minprice) > mprofit) {
mprofit = temp;
}
lprofit[i] = mprofit;
}
mprofit = 0;
rprofit[len - 1] = 0;
int maxprice = prices[len - 1];
//从右往左求price[n-1...i]最大受益
for (int j = len - 2; j >= 0; --j) {
if (maxprice < prices[j]) {
maxprice = prices[j];
}
if (mprofit < (temp = maxprice - prices[j])) {
mprofit = temp;
}
rprofit[j] = mprofit;
}
mprofit = 0;
for (int k = 0; k < len; ++k) {
if ((temp = lprofit[k] + rprofit[k]) > mprofit) {
mprofit = temp;
}
}
return mprofit;
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  小米