Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
fireairforce opened this issue Mar 9, 2020 · 0 comments
Open

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

fireairforce opened this issue Mar 9, 2020 · 0 comments

Comments

@fireairforce
Copy link
Owner

典型的dp问题,状态转移方程式为 第i天的最大收益 = max(第i - 1 天的收益,当天的价格 - 之前最小的价格)

/**
 * @param {number[]} prices
 * @return {number}
 */
var maxProfit = function(prices) {
    if(prices.length === 0) {
        return 0;
    }
   let dp = Array(prices.length).fill(0);
   let sum = prices[0];
   for(let i = 1;i<prices.length;i++) {
       dp[i] = Math.max(prices[i] - sum,dp[i -1]);
       if(sum > prices[i]) {
           sum = prices[i];
       }
   }
   return dp.sort((a,b)=>b-a)[0];
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant