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.
http://oj.leetcode.com/problems/best-time-to-buy-and-sell-stock/
Solution:
Simple DP, use two variables to update the lowest prices and max profit.
https://github.com/starcroce/leetcode/blob/master/best_time_to_buy_and_sell_stock.cpp
// 52 ms for 198 cases
class Solution {
public:
int maxProfit(vector<int> &prices) {
// IMPORTANT: Please reset any member data you declared, as
// the same Solution instance will be reused for each test case.
if(prices.size() < 1) {
return 0;
}
int lowest = prices[0], max = 0;
for(int i = 0; i < prices.size(); i++) {
int profit = prices[i] - lowest;
if(profit > max) {
max = profit;
}
if(prices[i] < lowest) {
lowest = prices[i];
}
}
return max;
}
};
本文介绍了一种简单有效的动态规划算法来解决股票交易中的最大利润问题。通过维护两个变量跟踪最低价格和最大利润,该算法能在O(n)的时间复杂度内找到给定股价数组的最佳买卖时机。

被折叠的 条评论
为什么被折叠?



