题目:
Say you have an array for which the i th 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.
题意:
假设有一个数组,其中第i个元素是某只股票在第i天的价格。
如果你最多只能完成一笔交易(即买一股和卖一股股票),设计一个算法来找出最大利润。
解题思路:
最大利润无非就是找出最大值和最小值的差
1.求出最小值
2.最大值只能在找出最小值之后得出,这是因为只有在买了之后才能卖出
代码:
public int maxProfit(int[] prices) {if(prices == null || prices.length <=0) {return 0;}int maxV = 0;int minV = prices[0];for(int i = 0; i<prices.length;i++) {minV = Math.min(minV, prices[i]);maxV = Math.max(maxV, prices[i] - minV);}return maxV;}