Program Trading (APCS 2022-01 Beginner)
Points 100 1.0s 256MXiaoming wants to trade stocks with a program. Given a stock's historical prices \(a[1], a[2], \ldots, a[n]\), his strategy is:
- He holds at most one share at a time, and buys at price \(a[1]\) at time \(1\).
- If he currently holds a share bought at price \(x\), then upon seeing a price \(y\) with \(y - x \ge D\) he sells it, gaining profit \(y - x\).
- If he currently holds no share and the previous sell price was \(x\), then upon seeing a price \(y\) with \(y \le x - D\) he buys.
Output the total profit obtained by following these rules. If he still holds a share when trading ends, that share's purchase cost is ignored (the share is simply disregarded).
Input
The first line contains two positive integers \(n\) and \(D\).
The second line contains \(n\) positive integers, the stock prices at each time point in order.
Constraints
- \(1 \le n, D \le 100\)
- \(1 \le a[i] \le 100\)
Output
Output a single integer, the total profit.
Scoring
The time limit for each test case is \(1\) second; your score is the sum over the test cases you pass. The subtasks are:
- Subtask 1 (\(50\) points): \(n = 3\).
- Subtask 2 (\(50\) points): no additional constraints.
Sample Input 1
3 10
50 20 45
Sample Output 1
0
Sample Input 2
6 10
30 20 45 38 10 20
Sample Output 2
25
Source
APCS programming exam, January 2022, Problem 1.
Log in to write and submit code.
Log in