题目
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.
一次买卖股票,求赚取最大值
1 如果暴力破解,把每天作为买入价,之后每天作为卖出价,两次循环。
2 考虑因为数组暗示地时序性,每次计算好之后,都可以算这天之前的最高价不用考虑了。所以,一次遍历数组,比最低价低的时候,替换最低价;比最低价高的时候,计算和最低价的差值,看看是否为maxprofit。
3 考虑递减数组,那么就不进行买卖,maxprofit为0,依然成立。
public class Solution {
public int maxProfit(int[] prices) {
if(prices.length<=1){
return 0;
}
int maxprofit = 0;
int buy = prices[0];
for(int i=1;i<prices.length;i++){
if(prices[i]<buy){
buy = prices[i];
}
else if(prices[i]-buy>maxprofit){
maxprofit = prices[i]-buy;
}
}
return maxprofit;
}
}