风口的猪

风口的猪

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

比如 3 8 5 1 7 8
输出 12
比较傻的方法:

public int calculateMax(int[] prices) {
        int len = prices.length;
         int max= 0;
        if(len<2)return 0;
        else if(len == 2) max =  prices[len-1] - prices[0] ;
        else if(len==3){
             
            max = (prices[2] - prices[0]>prices[2] - prices[1]?prices[2] -
                           prices[0]:prices[2] - prices[1]);
        }else{
             int left,right ;
            int max1 = 0;int max2=0;
            for(int p=0; p<len-1;p++){
                for(int q=p+1; q<len;q++){
                    if(max1 < prices[q] - prices[p]){
                        max1 = prices[q] - prices[p];
                    }
                }
            }
                 
            for(int i=0; i<len-3;i++){
                for(int j=i+1; j<len-2;j++){
                    left = prices[j]-prices[i];
                    for(int m=j+1; m<len-1;m++){
                        for(int n=m+1; n<len; n++){
                            right = prices[n] - prices[m];
                            if(max2 < left + right){
                                max2 = left +right;
                            }
                        }
                    }
                }
            }
             
            if(max1<max2){
                max = max2;
            }else{
                max = max1;
            }
        }
        
        if(max >0) return max ;
        else return 0;
         
    }

方法:

 public static int calculateMax(int[] prices) {
    
    	   int sum = 0;
    	    for(int i=1;i<prices.length;i++)
    	    {
	    	    int temp = getMax(prices,0,i)+getMax(prices,i,prices.length-1);
	    	    if(temp>sum) sum = temp;
    	    }

    	    return sum;
    }
    
    public static int getMax(int[] prices, int start,int end) {
    	int max =0;
    	int min = prices[start];
    	for(int i= start+1; i<=end;i++) {
    		if(prices[i]-min>max) {
    			max = prices[i]-min;
    		}
    		if(prices[i]<min) {
    			min = prices[i];
    		}
    	}
    	return max;
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值