一:题目
二:上码
class Solution {// public int maxProfit(int[] prices) {// int max= 0;// for (int i = 0; i < prices.length; i++) {// //求出i后面的最大值// int temp = 0;// for (int j = i + 1; j < prices.length; j++) {// if (prices[j] > temp) {// temp = prices[j];// }// }// if (temp > prices[i]) {// max = Math.max(temp - prices[i],max);// }// }// return max;// }public int maxProfit(int[] prices) {int minPrice = Integer.MAX_VALUE;int maxAns = 0;for (int i = 0; i < prices.length; i++) {if (minPrice > prices[i]) {//当计算最小值得时候 我们是不计算 差值的minPrice = prices[i];} else if (prices[i] - minPrice > maxAns) { //我们只有在价格往上升的时候才计算差值maxAns = prices[i] - minPrice;}}return maxAns;}
}