(超时。。。。。。)除了暴力法我是真的。。。。。。
class Solution {public int maxProfit(int[] prices) {int len = prices.length;int max=0;for(int i=0;i<len-1;i++){for(int j=i+1;j<len;j++){int income = prices[j] - prices[i];if(income>max){max=income;}}}return max;}
}
通过版
记录最低价格,计算最大利润,因为股票卖必须在买之后,所以只遍历一次数组即可!
class Solution {public int maxProfit(int[] prices) {int minprice = Integer.MAX_VALUE;int maxprofit = 0;for(int i = 0; i < prices.length; i++){if(prices[i] < minprice){minprice = prices[i];}else if(prices[i] - minprice > maxprofit){maxprofit = prices[i] - minprice;}}return maxprofit;}
}