动态规划问题之牛市重现!

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

public class Solution {
    /**
     * 计算你能获得的最大收益
     * 
     * @param prices Prices[i]即第i天的股价
     * @return 整型
     */
    public int calculateMax(int[] prices) {
 if(prices==null || prices.length==0 || prices.length<2 || prices.length>100){
            return 0;
        }

        int len = prices.length;
        int[] dpl = new int[len];
        dpl[0] = 0;
        int minI = 0; 
        for(int i=1; i<len; i++){   //从左到右扫描一遍填充dpl数组
            if(prices[i]>prices[i-1]){
                dpl[i] = Math.max(prices[i]-prices[minI],dpl[i-1]);
            } else{
                dpl[i] = dpl[i-1];
                if(prices[i]<prices[minI])
                    minI = i;
            }
        }

        int[] dpr = new int[len]; 
        dpr[len-1] = 0;
        int maxI = len-1;
        for(int i=len-2; i>=0; i--){//从右到左扫描一遍填充dpr数组
            if(prices[i]<prices[i+1]){
                dpr[i] = Math.max(prices[maxI]-prices[i], dpr[i+1]);
            } else{
                dpr[i] = dpr[i+1];
                if(prices[i]>prices[maxI]){
                    maxI = i;
                }
            }
        }

        int res = 0;
        for(int i=0; i<len; i++){ //比较得出最大值
            res = Math.max(dpl[i]+dpr[i], res);
        }
        return res;
    }
}

方法2:

static int prices[10] = {2,6,8,10,1,5,9,7,3,4};

static int result = 0;
int getmax(int star,int end){
    int min = prices[0]; int max = 0;
    for(int i = 1;i<10;i++){
        if(prices[i] - min > prices[max]){
            max = prices[i];
        }
        if(prices[i] < min){
            min = prices[i];
        }
        return max;
    }
} 
int calculateMax(){
    static int sum = 0;
    for(int i = 1 ;i < 10;i++ ){
        int temp = getmax(0,i) + getmax(i,9);
        if(temp > sum)
        {
            sum = temp;
        }
    }

    return sum;
}


int main(){
    cout<<calculateMax();
    system("pause");
    return 0;
} 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值