Leetcode——121. 买卖股票的最佳时机

题目描述:买卖股票的最佳时机

题目要求求解能获得最大利润的方式?

可以定一个二维数组 d [ len ] [ 2 ] ,其中d[ i ][ 0 ] 表示前i天可以获得的最大利润;d[ i ][ 1 ]表示前i天中股票最低的价格。

因此可以得到一个递推公式:

d[ i ] [ 0 ] = max(d[ i ][ 0 ] , prices[i] - a[i-1][1])

d[ i ] [ 1 ] = min(prices[ i ],a[ i -1 ][ 1 ]);

具体的代码如下:

class Solution {
    public int maxProfit(int[] prices) {
       int len = prices.length;
       if(len == 0){
           return 0;
       }
        int[][] a = new int[len][2];
        a[0][0] = 0;
        a[0][1] = prices[0];
        for(int i = 1 ; i < len ; i++){
            a[i][0] = Math.max(a[i-1][0],prices[i] - a[i-1][1]);
            a[i][1] = Math.min(prices[i],a[i-1][1]);
        }
        return a[len-1][0];
    }
}

猜你喜欢

转载自www.cnblogs.com/xiaxj/p/9692526.html
今日推荐