一、问题描述
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.
二、问题分析
初始化最低股价为第一天股价;
保证最高股价在最低股价出现之后。
三、算法代码
public class Solution {
public int maxProfit(int[] prices) {
if(prices.length < 2){
return 0;
}
int profit = 0;
int cur_min = prices[0];//初始化最低股价为第一天股价
for(int i = 0; i <= prices.length - 1; i++){
profit = Math.max(profit, prices[i] - cur_min);
cur_min = Math.min(cur_min, prices[i]);
}
return profit;
}
}