求后面的数减前面的数的最大差值,顺序遍历数组,如果遇到更小的数,就更新最小值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; } }
原文地址:https://www.cnblogs.com/y1040511302/p/11508203.html
时间: 2024-11-13 09:02:32