LeetCode Best Time to Buy and keep Stock

Source: Internet
Author: User

LeetCode Best Time to Buy and keep Stock
Best Time to Buy and Stock for LeetCode solving

Original question

Given the daily stock price, if only one round of trading is allowed, that is, the maximum profit can be obtained by buying and selling the stock once.

Note:

None

Example:

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

Output: 7 (buy when the price is 1 and sell when the price is 8)

Solutions

In the previous traversal of the series, we used the lowest price we have ever seen as the purchase price and calculated the benefits we have sold at the current price. During the whole traversal process, the biggest benefit we have ever seen is what we want.

AC Source Code
Class Solution (object): def maxProfit (self, prices): "": type prices: List [int]: rtype: int "if len (prices) <2: return 0 min_price = prices [0] max_profit = 0 for price in prices: if price <min_price: min_price = price if price-min_price> max_profit: max_profit = price-min_price return max_profitif _ name _ = "_ main _": assert Solution (). maxProfit ([2, 4, 6, 1, 3, 8, 3]) = 7

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.