LeetCode 121 Best Time to Buy and Buy Stock resolution (the Best Time to Buy and Sell stocks)

Source: Internet
Author: User

LeetCode 121 Best Time to Buy and Buy Stock resolution (the Best Time to Buy and Sell stocks)
Translation

In other words, you have an array where the I-th element indicates the stock price on the I-th day. If you are only allowed to trade at most once (for example, buy and sell a stock), design an algorithm and find the maximum profit.
Original
Say you have an array for which the ith element is the price of a given stock on day i.If you were only permitted to complete at most one transaction (ie, buy one and sell one share of the stock), design an algorithm to find the maximum profit.
Analysis

First, set the maximum profit and minimum profit:

If the current day's stock price is lower than the lowest price, set the lowest price to the day's stock price.

The reason is that we have to calculate the price is, of course, paving the way for the maximum profit.

If the maximum profit is lower than the minimum price for the current day, set the maximum profit to the current day price minus the lowest price.

Code
class Solution {public:    int maxProfit(vector
  
   & prices) {        size_t size = prices.size();        if (size <= 1) return 0;        int min = INT_MAX, max = INT_MIN;        for (int i = 0; i < size; ++i) {            if (prices[i] < min)                min = prices[i];            if (max < prices[i] - min)                max = prices[i] - min;        }        return max;    }};
  

Related Article

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.