Leetcode best time to Buy and Sell Stock II

Source: Internet
Author: User

Leetcode Problem solving best time to Buy and Sell Stock II original title

Given the daily stock price, if you allow multiple trades, you can buy and sell multiple times, but only one stock is held at most, and when you buy again, you must sell the previous stock for the maximum profit you can get.

Note the point:

    • No

Example:

Input: Prices = [2, 4, 6, 1, 3, 8, 3]

Output: 11 ([2,6], [1,8] is the time to buy and sell two times)

Thinking of solving problems

Multiple trades can be made, in order to obtain the most profit, should buy at the beginning of the interval of each price rise, sell at the end. Iterate over the array before, and if the price goes down, sell it the day before and buy it again on the date of the fall. Do not forget that there is no downside after the last ascent and add extra.

AC Source
 class solution(object):     def maxprofit(self, prices):        "" : Type Prices:list[int]: Rtype:int " " "        if  notPrices:return 0Low = High = prices[0] Profit =0         forIinchRange1, Len (prices)):ifPrices[i] >= prices[i-1]: High = prices[i]Else: Profit + = high-low Low = high = Prices[i] Profit + = high-lowreturnProfitif__name__ = ="__main__":assertSolution (). Maxprofit ([2,4,6,1,3,8,3]) == One

Welcome to my GitHub (Https://github.com/gavinfish/LeetCode-Python) to get the relevant source code.

Leetcode best time to Buy and Sell Stock II

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.