Leetcode: best_time_to_buy_and_sell_stock

Source: Internet
Author: User

I. Question

The same is to buy and sell stocks, to find the maximum profit, but only buy and sell once.

Ii. Analysis

Since it can only be bought and sold once, the purchase must be in the front of the sell, so we can traverse the array, each time save the current maximum profit and the current minimum value, each passing through a value, the current value is used to subtract the minimum value from the previous one and the maximum profit is greater, and the current value and the minimum value are smaller until the end.

Note: Check the number of elements in the array before traversing!

 

Other good methods: http://blog.csdn.net/ithomer/article/details/7107968

 

class Solution {public:    int maxProfit(vector<int> &prices) {        if(prices.size()<=1) return 0;int profit=0;int current_min=prices[0];for(int i=0;i<prices.size();i++) {profit=max(profit,prices[i]-current_min);current_min=min(current_min,prices[i]);}return profit;    }};class Solution {public:    int maxProfit(vector<int> &prices) {        if(prices.size()<=1) return 0;        int max_profit=0;int min_price=prices[0];for(int i=0;i<prices.size();i++) {if(prices[i]-min>max_profit) max_profit=prices[i]-min;if(prices[i]<min_price) min_price=prices[i];}return max_profit;    }};


Leetcode: best_time_to_buy_and_sell_stock

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.