import java.util.*; public class Solution { /** * * @param prices int整型一维数组 * @return int整型 */ public int maxProfit (int[] prices) { if(null == prices || prices.length == 0){ return 0; } int bestResult = 0; int buyPrice = prices[0]; for(int i=1;i<prices.length;i++){ //最便宜的时候买 最高的时候卖 才是最划算的 //如: [8,1,2,3,4,9] 1块钱买 9块钱卖 //如: [1,2,3,4,5,9] 1块钱买 9块钱卖 //如: [8,16,1,1,1] 8块钱买 16块钱卖 //如: [9,8,7,6,5,4,3,2,1] 应该是1块钱买 1块钱卖 buyPrice = Math.min(buyPrice,prices[i]); bestResult = Math.max(bestResult,prices[i]-buyPrice); } return bestResult; } }