leetcode 121.买卖股票的最佳时机(java 贪心)
求后面的数减前面的数的最大差值,顺序遍历数组,如果遇到更小的数,就更新最小值minn,依次判断prices[i]-minn的值,更新maxx。
class Solution { public int maxProfit(int[] prices) { int len=prices.length; if(len==0) return 0; int minn=prices[0]; int maxx=0; for(int i=1;i<len;i++){ if(prices[i]>minn&&prices[i]-minn>maxx){ maxx=prices[i]-minn; } if(prices[i]<=minn){ minn=prices[i]; } } return maxx; } }