Best Time to Buy and Sell Stock
Total Accepted: 49995 Total Submissions: 153488My Submissions
Question Solution
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.
Hide Tags
Have you met this question in a real interview?
Yes
No
分析:找最小最大值,计算最大利益
public class Solution {
public int maxProfit(int[] prices) {
int l=prices.length;
if(l<=1)
return 0;
else
{
int min=prices[0];
int max=prices[0];
int maxp=0;
int oldmaxp=0;
for(int i=1;i<l;i++)
{
if(prices[i]<min)
{
min=prices[i];
max=prices[i];
if(maxp>oldmaxp)
oldmaxp=maxp;
}
else
{
if(prices[i]>max)
{
max=prices[i];
maxp=max-min;
}
}
}
if(maxp>oldmaxp)
return maxp;
else
return oldmaxp;
}
}
}