rocksc30 / LeetCode

用于力扣刷题打卡
2 stars 0 forks source link

121. 买卖股票的最佳时机 #62

Open rocksc30 opened 1 year ago

rocksc30 commented 1 year ago
class Solution {
    public int maxProfit(int[] prices) {
        // this is ans
        int max = 0;
        // int minPrices = Integer.MAX_VALUES;

        // 使用 dp[i]表示截止到第i天的最低价格
        int[] dp = new int[prices.length];
        // 初始化dp数组
        dp[0] = prices[0];

        for(int i = 1; i < prices.length; i++){
            dp[i] = dp[i - 1] > prices[i] ? prices[i] : dp[i - 1];
            max = (prices[i] - dp[i]) > max ? (prices[i] - dp[i]) : max;
        }
        return max;
    }
}
Ni-Guvara commented 1 year ago
class Solution {
public:
    int maxProfit(vector<int>& prices) {
        int maxProfit = 0;
        int minPirce = INT_MAX;
        int len = prices.size();

        for(int i = 0 ; i < len ;i++)
        {
            maxProfit = max(maxProfit , prices[i] - minPirce);
            minPirce = min(minPirce,prices[i]);
        }

        return maxProfit;

    }
};