题解 | #买卖股票的最好时机(二)#
买卖股票的最好时机(二)
https://www.nowcoder.com/practice/fbc5dad3e215457fb82a3ae688eb7281
import java.util.Scanner; public class Main { public static int solution(int[] prices) { int buy = 0; int res = 0; for (int i = 1; i < prices.length; i++) { // 只要下降,就在前一天卖出,且当天买入 if (prices[i] < prices[i - 1]) { // 不是连续下降的场景 if (buy != i - 1) { res += prices[i - 1] - prices[buy]; } buy = i; } } // 边界处理 if (buy != prices.length - 1) { res += prices[prices.length - 1] - prices[buy]; } return res; } public static void main(String[] args) { Scanner in = new Scanner(System.in); int n = in.nextInt(); int[] prices = new int[n]; for (int i = 0; i < prices.length; i++) { prices[i] = in.nextInt(); } System.out.println(solution(prices)); } }