【ATT】Best Time to Buy and Sell Stock
Q: 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.
A: Find i and j that maximizes Aj - Ai, where i < j.
int maxProfit(vector<int> &prices) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
if(prices.empty())
return 0;
int maxDiff = 0;
int cur,min = 0;
for(cur=0;cur<prices.size();cur++)
{
if(prices[cur]<prices[min])
min = cur;
if(prices[cur] - prices[min] > maxDiff)
maxDiff = prices[cur] - prices[min];
}
return maxDiff;
}
浙公网安备 33010602011771号