Best time to buy and keep stock I, II, III [leetcode]

Source: Internet
Author: User

Best time to buy and buy stock I

Only one operation: Minimum value that appears before the premin record is maintained

The Code is as follows:

    int maxProfit(vector<int> &prices) {        if (prices.size() == 0) return 0;        int profit = 0;        int preMin = prices[0];        for (int i = 1; i < prices.size(); i++)        {            if (prices[i] < preMin) preMin = prices[i];            profit = max(profit, prices[i] - preMin);        }        return profit;    }

Best time to buy and stock Stock II

Unlimited operation: When ==> current price> purchase price, sell

The Code is as follows:

    int maxProfit(vector<int> &prices) {        if (prices.size() == 0) return 0;        int profit = 0;        int buy = prices[0];        for (int i = 1; i < prices.size(); i++)        {            if (buy < prices[i])                profit += prices[i] - buy;            buy = prices[i];        }        return profit;    }

Best time to buy and buy stock III

Only two operations can be performed:

The two operations cannot overlap and can be divided into two parts: 0 .. I maximum profit FST and I .. n-1 maximum profit SND

The Code is as follows:

    int maxProfit(vector<int> &prices) {        if (prices.size() == 0) return 0;        int size = prices.size();        vector<int> fst(size);        vector<int> snd(size);                int preMin = prices[0];        for (int i = 1; i < size; i++)        {            if (preMin > prices[i]) preMin = prices[i];            fst[i] = max(fst[i - 1], prices[i] - preMin);        }        int profit = fst[size - 1];        int postMax = prices[size - 1];        for (int i = size - 2; i >= 0; i--)        {            if (postMax < prices[i]) postMax = prices[i];            snd[i] = max(snd[i + 1], postMax - prices[i]);            //update profit            profit = max(profit, snd[i] + fst[i]);        }        return profit;    }


Best time to buy and keep stock I, II, III [leetcode]

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.