Leetcode_num5_best time to buy and invalid stock II

Source: Internet
Author: User

Question:

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

Design an algorithm to find the maximum profit. you may complete as your transactions as you like (ie, buy one and every one share of the stock multiple times ). however, you may not engage in multiple transactions at the same time (ie, you must wait the stock before you buy again ).

I have been busy from the weekend to work days, but I still cannot relax my questions ~~~ (I don't know how long I can stick to it, hahaha)

The difficulty of this question mainly lies in understanding the question and thinking transformation. Because of the stock background, the code is quite simple,... I still fell into the trap... Tears

SetBuying and selling are regarded as a roundTo maximize profits, you only need to meet the principles of low-price purchase and high-price sales.

For example, if prices = [3, 1, 4, 6, 5, 7]

Then, you can buy at 1, 4, 4, 6, 5, and 7.

In this way, total (4-1) + (6-4) + (7-5) = 7

The final code is as follows:

class Solution:    # @param prices, a list of integer    # @return an integer    def maxProfit(self, prices):        L=len(prices)        rs=0        for i in range(0,L-1):            if prices[i+1]>prices[i]:                rs+=(prices[i+1]-prices[i])        return rs




Leetcode_num5_best time to buy and invalid 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.