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.
Subscribe to see which companies asked this question
1 public class Solution { 2 public int maxProfit(int[] prices) { 3 if(prices.length == 0 || prices.length == 1) return 0; 4 int maxvalue = 0;//最大值默认为0 5 int min = 0;//设置前i-1个最小值的位置 6 for(int i = 1;i<prices.length;i++){ 7 if(prices[i] > prices[min]) maxvalue = prices[i] - prices[min] > maxvalue ? prices[i] - prices[min] : maxvalue; 8 if(prices[i] < prices[min]) min = i; 9 } 10 return maxvalue; 11 } 12 }
min 标志前i-1个中最小值的index,maxvalue 设置默认最大值。
整体思路是若第i个值大于前i-1个值中最小的,则减去prices[min] 与maxvalue进行比较,取最大值。遍历一遍即可。