Leetcode Best Time to Buy and Sell Stock

來源:互聯網
上載者:User

標籤:des   style   class   blog   code   color   

Say you have an array for which the ith element is the price of a given stock on day i.

If you were only permitted to complete at most one transaction (ie, buy one and sell one share of the stock), design an algorithm to find the maximum profit.

一開始看到題目以為是最大值減去最小值即可,但由於買發生在賣前面,所以,最小值買進最大值賣出只有在最小值在最大值前面時才發生

本題思路是:遍曆時記錄前面最小值點,然後max(當前元素-前面最小值)即可

class Solution {public:    int maxProfit(vector<int> &prices) {        if(prices.size() == 0) return 0;        int res = 0, minv = prices[0];        for(int i = 1; i < prices.size(); ++ i){            res = max(res,prices[i]-minv);            minv = min(prices[i],minv);        }        return res;    }};

本題也可以考慮利用動態規划去做

設決策變數為dp[i],表示i個元素賣出的最大利潤

則狀態轉移方程為

  dp[i+1] = prices[i+1]-prices[i]+max(0,dp[i])

由於前面的dp[i],在dp[i+1]後不會被使用,故只需要一個狀態變數,不斷更新這個狀態變數即可

class Solution {public:    int maxProfit(vector<int> &prices) {        int dp = 0, res = 0;        for(int i = 1; i < prices.size(); ++ i){            dp = prices[i]-prices[i-1] + max(0,dp);            res = max(res,dp);        }        return res;    }};

 

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.