首页 > 其他 > 详细

股票买卖最佳时机

时间:2020-07-13 18:44:31      阅读:59      评论:0      收藏:0      [点我收藏+]

股票1(只买卖1次)

技术分享图片
注意:这个不仅仅是找到数组最大最小就行了,注意时间顺序

class Solution {
    public int maxProfit(int[] prices) {
     if(prices.length==0||prices==null) return 0;
     int max=0,min=prices[0];
     for(int price : prices ){
       min = price < min? price : min;//找到截止访问当前元素的最小值
       max = price-min > max? price-min : max;
     }
     return max;
    }
}

技术分享图片

股票2(买卖多次)

技术分享图片
技术分享图片

解法1:动态规划(划分2个状态,持有现金和持有股票)

class Solution {
    public int maxProfit(int[] prices) {
        int len = prices.length;
        int [][]f = new int[len][2];

        //f[i][0],第i天持有现金的收益
        //f[i][1],第i天持有股票的收益
      
        f[0][0]=0;//初始持有现金0
        f[0][1]=-prices[0];//初始没钱买了股票
        for(int i=1;i<len;i++){
         f[i][0]=Math.max(f[i-1][1]+prices[i],f[i-1][0]);//今天有钱,收益Max(昨天的收益,昨天有股票今天卖了)
         f[i][1]=Math.max(f[i-1][0]-prices[i],f[i-1][1]) ;//今天有股票,收益 Max(昨天有股票的收益,昨天没有今天买了股票的收益)
          
        }
        return f[len-1][0];
    }
}

解法2:贪心
技术分享图片

class Solution {
    public int maxProfit(int[] prices) {
        int len = prices.length;
        int res=0;
        for(int i=1;i<len;i++){
        if(prices[i]>prices[i-1])
        res += prices[i]-prices[i-1];
        }
        return res;
    }
}

股票3(买卖多次含手续费)

动态规划,这道题不能用贪心


class Solution {
    public int maxProfit(int[] prices, int fee) {
         int len = prices.length;
        int [][]f = new int[len][2];

        //f[i][0],第i天持有现金的收益
        //f[i][1],第i天持有股票的收益
      
        f[0][0]=0;//初始持有现金0
        f[0][1]=-prices[0];//初始没钱买了股票
        for(int i=1;i<len;i++){
         f[i][0]=Math.max(f[i-1][1]+prices[i]-fee,f[i-1][0]);//今天有钱,收益Max(昨天的收益,昨天有股票今天卖了)
         f[i][1]=Math.max(f[i-1][0]-prices[i],f[i-1][1]) ;//今天有股票,收益 Max(昨天有股票的收益,昨天没有今天买了股票的收益)
          
        }
        return f[len-1][0];
    }
}

股票买卖最佳时机

原文:https://www.cnblogs.com/cstdio1/p/13294653.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!