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.
一开始使用了暴力方法,但是提示 Time Limit Exceeded
public class Solution {
public int maxProfit(int[] prices) {
int maxPro = 0;
for (int i = prices.length - 1; i > 0; i--) {
for (int j = i - 1; j >= 0; j--) {
if (prices[i] - prices[j] > maxPro) {
maxPro = prices[i] - prices[j];
}
}
}
return maxPro;
}
}
改进了一下,遍历一遍,找出价格最低的和价格最高的,并且要求价格最低项要在价格最高项之前出现。
参考:http://www.myexception.cn/other/1671339.html
public class Solution {
public int maxProfit(int[] prices) {
if(prices.length ==0)
return 0;
int i=0;
int profit=0;
int begMin= prices[0];
for(i=1; i<prices.length; ++i){
profit=Math.max(profit, prices[i]-begMin);
begMin=Math.min(begMin, prices[i]);
}
return profit;
}
}