小米笔试题 风口的猪-中国牛市
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
风口之下,猪都能飞。当今中国股市牛市,真可谓“错过等七年”。 给你一个回顾历史的机会,已知一支股票连续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; } }
相关文章推荐
- 雷军是谁,他为什么而奋斗?小米上市和雷军的英雄主义
- android开发教程之ubuntu使用adb连接小米2的步骤和adb调试方法
- Android判断手机是否是小米MIUI系统的方法
- 知道你们为什么抢不到红米吗?来看看这个
- 小米马上要上市?雷军说:我们态度没变化
- 为什么迄今人们还没有看懂雷军和小米?
- 华为OR小米,谁是智能手机出货量之王?
- 360再诉小米:一场利益之争的诉讼“罗生门”
- 小米电饭煲到底值不值?
- 用Python(Tornado)模拟登录小米帐号
- eclipse连接android设备的问题
- 揭开智能硬件的严肃面纱,展示智能产品的娱乐情怀
- 小米双剑出鞘,红米2、小米4S所到之处尸横满地?
- 红米2打冲锋,小米5拼刺刀,与魅族荣耀肉搏到底
- 树莓派2使用360wifi ,小米wifi
- 小米手机不支持对去电的拦截解决方案(BroadcastReceiver)
- 魅族小米化后 几家欢喜几家愁?