算法 BISHI51 低买高卖 思路 求解代码 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); PrintWriter out = new PrintWriter(new OutputStreamWriter(System.out)); int n = Integer.parseInt(br.readLine()); String[] str = br.readLine().split("\\s+"); long[] p = new long[n]; for (int i = 0; i < n; i++) { p[i] = Long.parseLong(str[i]); } PriorityQueue<Long> minHeap = new PriorityQueue<>(); // 小顶堆:堆顶始终是当前堆中最小值 long profit = 0; // 初始化总利润为0 for (int i = 0; i < n; i++) { minHeap.add(p[i]); // 将当前价格加入堆 if (minHeap.peek() < p[i]) { // 如果堆顶(当前最低价格)< 当前价格 → 可以低买高卖 long buy = minHeap.poll(); // 取出堆顶(买入价) profit += p[i] - buy; // 累加本次利润(当前价-买入价) minHeap.add(p[i]); // 把当前价格重新入堆(相当于“卖出后再以当前价买入”,继续后续交易) } } out.println(profit); out.flush(); out.close(); br.close(); }