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

      风口之下,猪都能飞。当今中国股市牛市,真可谓“错过等七年”。 给你一个回顾历史的机会,已知一支股票连续n天的价格走势,以长度为n的整数数组表示,数组中第i个元素(prices[i])代表该股票第i天的股价。 假设你一开始没有股票,但有至多两次买入1股而后卖出1股的机会,并且买入前一定要先保证手上没有股票。若两次交易机会都放弃,收益为0。 设计算法,计算你能获得的最大收益。 输入数值范围:2<=n<=100,0<=prices[i]<=100 

解体思路:

    考虑题目限制,至多卖出一次,买入可以1次/2次/0次,也就是低买高卖,计算max{第一次卖出-第一次买入}+max{第二次持有最高值-第二次买入},第二次可有可无,因此以第一次卖出为分界线,分别计算max{第一次卖出-第一次买入},右边计算max{第二次持有最高值-第二次买入};

代码:

public class Solution {

	/**
     * 计算你能获得的最大收益
     * 
     * @param prices Prices[i]即第i天的股价
     * @return 整型
     */
    public int calculateMax(int[] prices) {
    	int[] lprofit=new int[prices.length];//存放max{第一次卖出-第一次买入}
    	int[] rprofit=new int[prices.length];//存放max{第二次持有最高值-第二次买入}
    	
    	//从左到右循环
    	int maxProfit=0;//计算已有的最大收益
    	int minPrice=prices[0];//已经获得的最小值
    	for(int i=0;i<prices.length;i++){
    		if(minPrice>prices[i]){
    			minPrice=prices[i];
    		}
    		if(maxProfit< (prices[i]-minPrice)){//最大值产生比较
    			maxProfit=(prices[i]-minPrice);
    		}
    		lprofit[i]=maxProfit;	
    	}
    	//从右到左循环
        maxProfit=0;
        rprofit[prices.length-1]=0;
        int maxPrice = prices[prices.length-1];
        minPrice=prices[prices.length-1];
    	int temp;
        for(int j=(prices.length-2);j>=0;j-- ){
    		if(maxPrice<prices[j]){
    			maxPrice=prices[j];
    		}   		
    		if(maxProfit<(temp=maxPrice-prices[j])){
    			maxProfit=temp;	
    		}
    		rprofit[j]=maxProfit;
    	}
        
        //计算总和
        maxProfit=0;
        for(int i=0;i<prices.length;i++){
        	if((temp=lprofit[i]+rprofit[i]) >maxProfit ){
        		maxProfit=temp;
        	}
        	
        }
        return maxProfit;
    }
}


评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值