一次遍历,一边遍历一边修改买入的价格,一边比较取得最大利润
public class BuyAndSellStocks {public static void main(String[] args) {int[] arr = {7,1,5,3,6,4};int[] arr1 = {7,6,4,3,1};System.out.println(buyAndSellStocks(arr));System.out.println(buyAndSellStocks(arr1));}public static int buyAndSellStocks(int[] prices) {int buy = prices[0];//初始买入价格int profit = 0;//赚取利润for (int i = 0; i < prices.length; i++) {if (i < prices.length - 1 && prices[i] < buy) {//肯定要在倒数第二天前买入buy = prices[i];//修改买入的价格}profit = Math.max(prices[i] - buy, profit);//prices[i] - buy和profit取较大值}return profit;}
}