股票买卖最佳时机

股票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];
    }
}
posted @ 2020-07-13 17:57  浅滩浅  阅读(149)  评论(0编辑  收藏  举报