Leetcode: best time to Buy and Sell-Cooldown_leetcode

Source: Internet
Author: User

Say you have an array for which the ith element are the price of a given the

Design a algorithm to find the maximum profit. You may complete as many transactions as (ie, buy one and sell one share of the "stock multiple times") with the FO Llowing Restrictions:

The May isn't engage in multiple transactions at the same time (ie, your must sell the stock before your buy again).
After you sell your the stock, your cannot buy the stock on next day. (ie, cooldown 1 day)
Example:

Prices = [1, 2, 3, 0, 2]
Maxprofit = 3
transactions = [Buy, Sell, cooldown, buy, sell]

Given an array, I represents the price of the stock in the first day. Ask for the maximum yield, the number of transactions you want to make, and you can buy and sell the same stock multiple times. But one stock can only be traded at a time (not multiple at the same time) and must be sold before it can be bought and a day's rest after sale.

The idea of solving problems: Dynamic programming

Code:

 public int Maxprofit (int[] prices) {int sell = 0, Prev_sell = 0, buy = integer.min_value, prev_buy;
        for (int price:prices) {prev_buy = buy;
        Buy = Math.max (Prev_sell-price, prev_buy);
        Prev_sell = sell;
    Sell = Math.max (prev_buy + price, Prev_sell);
return sell; }

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.