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