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;
}
};