假设有一个数组,它的第i个元素是一支给定的股票在第i天的价格。如果你最多只允许完成一次交易(例如,一次买卖股票),设计一个算法来找出最大利润。
样例
给出一个数组样例 [3,2,3,1,2], 返回 1
解题思路:和最大子数组的思路类似,保存一个当前最小值,每次算当前元素和最小值的差是否为最大。
一刷ac
public class Solution {
/**
* @param prices: Given an integer array
* @return: Maximum profit
*/
public int maxProfit(int[] prices) {
if(prices == null || prices.length == 0) return 0;
int profit = 0;
int min = prices[0];
for(int i = 1; i < prices.length; i++){
profit = Math.max(profit, prices[i] - min);
if(min > prices[i]) min = prices[i];
}
return profit;
}
}