动态规划:剑指 Offer 63. 股票的最大利润

发布时间 2023-04-18 15:00:28作者: ZDREAMER

题目描述:

假设把某股票的价格按照时间先后顺序存储在数组中,请问买卖该股票一次可能获得的最大利润是多少?

 

限制:

  0 <= 数组长度 <= 10^5

 

 

 

 

class Solution{
    public int maxProfit(int prices[]){
        //状态定义:dp[i]记为利润 profit
        // 前 i日的最低价格 min(prices[0:i])记作cost
        int cost = Integer.MAX_VALUE,profit=0;//初始化
        for(int price:prices){
            cost = Math.min(cost,price);
            profit = Math.max(profit,price-cost);//状态转移
        }
        return profit;//返回值
    }
}

 

动态规划四部曲:1.状态定义 2.状态转移 3.初始化 4.返回值