題目
假設(shè)有一個數(shù)組,它的第i個元素是一支給定的股票在第i天的價格。如果你最多只允許完成一次交易(例如,一次買賣股票),設(shè)計一個算法來找出最大利潤。
樣例
給出一個數(shù)組樣例 [3,2,3,1,2], 返回 1
分析
貪心法,一個記錄目前為止的最小值,一個記錄目前的最大profit,隨時更新即可
代碼
public class Solution {
/**
* @param prices: Given an integer array
* @return: Maximum profit
*/
public int maxProfit(int[] prices) {
// write your code here
if(prices == null || prices.length == 0)
return 0;
int min = Integer.MAX_VALUE; //store the min value that until now;
int profit = 0; //store the profit, initial value is zero;
for(int i:prices) {
min = Math.min(min, i);
profit = Math.max(profit, i-min);
}
return profit;
}
}