标签:
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.
解题思路:第一个思路是循环遍历购买日和卖出日,然后计算最后最大的利润;结果超时了.第二个思路是由数组末端开始遍历购买日,同时记录卖出价值最高对应的下坐标.
#include<iostream> #include<vector> using namespace std; //一般遍历:超时 int maxProfit(vector<int> &prices) { int MaxPro = INT_MIN; for (int d_buy = 0; d_buy < prices.size();++d_buy){ for (int d_sell = d_buy + 1; d_sell < prices.size();++d_sell) { int Profit = prices[d_sell] - prices[d_buy]; MaxPro = MaxPro < Profit ? Profit : MaxPro; } } return MaxPro; } //记录最大卖出价格日:AC int maxProfit(vector<int> &prices) { int MaxPro = 0; if (prices.size() < 2) return 0; for (int d_buy = prices.size() - 2, d_sell = prices.size() - 1; d_buy >= 0; --d_buy) { int Profit = prices[d_sell] - prices[d_buy]; if (Profit<0) d_sell = d_buy; else MaxPro = MaxPro < Profit ? Profit : MaxPro; } return MaxPro; }
Best Time to Buy and Sell Stock
标签:
原文地址:http://blog.csdn.net/li_chihang/article/details/44056155