package org.example.interview.practice; import java.util.List; /** * @author xianzhe.ma * @date 2021/7/13 */ public class NC_7_MAXPROFIT { public static int maxProfit(int[] prices) { int minV = prices[0]; int profit = 0; //初始化minV和profit; for (int i = 0; i < prices.length; i++) //遍历完,求出每一位处的最大收益,永远取minv的最小值和profit的最大值 { if (minV > prices[i]) { minV = prices[i]; //如果找到了更小的,替换; } profit = Math.max(profit, prices[i] - minV); //每次都求profit,所有的遍历完即可找到最大值; } return profit; } public static void main(String[] args) { int[] arr = {8, 9, 2, 5, 4, 7, 1}; System.out.println(maxProfit(arr)); } }