Best Time to Buy and Sell Stock
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.
这个问题挺有意思,刚开始想到了DP,和最大递增子列有点像 C[i] = max{0 < j < i C[j] + A[j] - A[i] } 最后max_profit = max{C[i], 0 <= i < n},这个算法的效率明显是O(n^2),即使将C[j]用数组B组织可以二分查找,平均情况下的复杂度也是O(nlog(n)).
看了别人的实现,有更简单的思路:假设在i处买入,那么 i+1~n的最大股价相对于i能获得最大的利润。只要从后往前,在计算最大利润的时候顺便存储最大价格,那么就是O(n)的复杂度了。
class Solution { public: int maxProfit(vector<int> &prices) { // Start typing your C/C++ solution below // DO NOT write int main() function int max_profit = 0; int max_price = 0; for(int i = prices.size() -1; i >= 0; i--){ if (prices[i] > max_price){ max_price = prices[i]; } if (max_price - prices[i] > max_profit){ max_profit = max_price - prices[i]; } } return max_profit; } };
浙公网安备 33010602011771号