classSolution{ publicintmaxProfit(int[] prices){ int minPrice = 100001, profit = 0; int length = prices.length; for(int i = 0; i < length; i++) { if (minPrice > prices[i]) { minPrice = prices[i]; } elseif (prices[i] - minPrice > profit) { profit = prices[i] - minPrice; } } return profit; } }
Swift
1 2 3 4 5 6 7 8 9 10 11 12
classSolution{ funcmaxProfit(_prices: [Int]) -> Int { var profit =0//记录最大利润 var minValue: Int= prices[0] //记录数组中访问过的最小值 let n = prices.count for i in0..< n { minValue =min(minValue, prices[i]) profit =max(prices[i] - minValue, profit) } return profit } }