We need to solve the classic "stock maximize" problem: given future prices, you can buy one share per day (at most one?), and sell any number of shares on any day. The goal is to maximize profit.
Wait: The description: "Each day, you can either buy one share of M&M, sell any number of shares of M&M that you own, or not make any transaction at all." So on each day, you have three options: buy exactly one share (if you have enough money? But they assume unlimited funds? Usually in such problems, you can buy one share per day, and you can sell any number. The profit is computed as total money from sales minus total money spent on purchases. Typically there is no initial capital constraint; we assume you can borrow money to buy shares and later pay back, so profit is net. However, careful: In many stock maximize problems on Hackerrank, the constraints are similar: You can buy at most one share each day, and sell any number. They ask for maximum profit. And solution is: traverse from the end, keep max future price, sum (max - price_i) for each day if price_i < max. But that algorithm assumes you can buy as many shares as you want? Actually if you can buy at most one per day, then the total profit is sum over days where price_i < max_future_i of (max_future_i - price_i). That gives the maximum profit, as you would buy on days where future higher price exists and sell on the day of that max price (or later). But careful: The classic Hackerrank problem "Stock Maximize" has the exact same description: "Each day, you can either buy one share of M&M, sell any number of shares, or do nothing. Find maximum profit." And the solution is indeed to go from right, keep a current max, add max - price if price < max. So it's consistent.
But note: There is nuance: The sell operation: "sell any number of shares of M&M that you own". So you can sell multiple on the same day. So indeed, if we have a high price day, we want to sell all shares bought earlier that have not been sold. And we can buy at most one share per day. So the strategy: For each day, decide whether to buy that day's share (if it's beneficial) and later sell at some future day with maximum price (the highest among future days). However, if there are multiple peaks, you might want to sell some shares earlier and then buy again later. But the algorithm that sums (max_future - price) for each day where price < max_future yields the correct total profit. Explanation: Starting from the end, keep the maximum price seen so far to the right. For each day, if the price is less than that maximum, we can buy the share today and later sell at the maximum price day, gaining that difference. If there is a higher maximum later after that maximum day? Actually, if we have multiple peaks, we need to consider that we might want to sell some shares earlier and then buy later. The algorithm using the current maximum from the right ensures that we always compare with the maximum after today. But what about a case where we might want to sell at an earlier peak and then buy again before a later peak? The algorithm still works because it effectively buys on days when price is less than some future maximum, and sells at the future maximum day, but if there are multiple maxima, the algorithm would use the global maximum to the right, which might be after an earlier peak. However, could it be better to sell at an earlier peak and then buy again before a later peak? Let's think: Suppose prices: [1,3,5,3,4]. The global maximum to the right of day 1 is 5, day 2: max right = 5, day 3: max right = 4? Actually day 3: right includes day 4 price 3, day 5 price 4, max=4. So day3 price=5, max right=4, so no buy. Day4 price=3, max right=4, so buy and sell at day5. Day5: no buy. Also day1 buy and sell at day3? But algorithm says for day1, max right = max(3,5,3,4)=5, so buy day1 and sell at day3 (the max). Actually the maximum is at day3 (price 5). So day1 buy and sell at day3 profit 4. Day2 price=3, max right=5 (day3) so buy and sell at day3 profit 2. So total profit =6. But is it possible to get more? Strategy: Buy day1 (1), day2 (3). Sell both on day3 at 5: profit = (5-1)+(5-3)=6. Or alternative: Sell day2's share on day2? No, selling on day2 at 3 gives zero profit. Could also buy day4 at 3 and sell day5 at 4: profit 1. So total if you also buy day4: but then you would need to not have sold earlier? Actually you can also do: Buy day1, sell day3; buy day2, sell day3; buy day4, sell day5; profit=4+2+1=7. But is it allowed? After selling on day3, you still have money, and you can buy on day4. So that's valid. But does the algorithm include buying on day4? Yes, because for day4, max right =4, price=3, so adds 1. So total profit computed as sum for days 1,2,4 = (5-1)+(5-3)+(4-3)=4+2+1=7. But wait, is day3 considered? price 5, max right=4, no addition. So total 7. But earlier I computed 6 forgetting day4. So algorithm gives 7. But is that valid? Check: Buy day1 (cost 1), day2 (cost 3). Day3: price 5, you can sell any number. So sell both shares (profit: you get 5*2 =10, cost total 1+3=4, net 6). Then on day4, you can buy one share at price 3 (cost 3). Day5 sell at 4 (receive 4). Total net: 10 - 4 =6, then 4-3=1, overall 7. Yes works. So algorithm yields optimal.
Thus solution: for each test case, given array P of length N, we compute max from the right, and for each i from 0 to N-1, if P[i] < current_max, add current_max - P[i] to profit. Otherwise if P[i] >= current_max, update current_max = P[i].
But careful: When P[i] == current_max, we don't add profit because buying at the same price as future max yields no profit; but we also might want to update? Actually if P[i] == current_max, there is no profit from buying today and selling later at same price (since no profit). And since we have the current_max as P[i], for future days (to the left) we want the maximum future price, which is at least P[i]; but if there are equal values, using >= ensures we update to this value, but it might not matter: if we keep current_max as the maximum seen so far, and if we encounter a price equal to current_max, we should not add profit, and we might either keep current_max unchanged or set it to this price; either way, for days left of i, the maximum to the right is at least this price. Since it's equal, it's fine. But note: If there is a later price that is also equal, but we might need to decide where to sell? Since profit zero if buy at price equal to max, it doesn't matter. So updating current_max to the new equal value is okay; but if we don't update, we would still have the same max. However, the algorithm typically updates if P[i] > current_max, but for equal, some implementations don't update; but it doesn't affect the result because for days to left, the max remains same. But careful: Consider scenario: prices: [5,4,5]. Starting from rightmost, max=5 (last). For i=1 (4), 4<5 add 1. For i=0 (5), 5<5? No, equal. So profit=1. If we had updated max at i=0? Actually from right to left: start max=5 at i=2. i=1: price=4<max, profit+=1. i=0: price=5, if we update max to 5 (it's already 5) or keep, no profit. So correct. If we had updated max to 5 (but it's same) no issue. But consider [5,5,4]. Start max=4 at i=2? Actually from right: i=2 price=4, max=4. i=1 price=5, 5 > max => update max=5, no profit. i=0 price=5, 5<max? 5<5 false, so no profit. Profit=0. This is correct: cannot make profit. So update when encountering larger or equal? If we update on equal at i=1, we set max=5; then i=0: price=5, compare 5<5 false, profit remains 0. Same. So either works.
Thus algorithm is straightforward.
Now constraints: N up to 50000, T up to 10, so O(N) per test case fine.
Edge cases: N=0? But N>=1.
But also note: The sample input and output match this algorithm.
Thus solution: For each test case, read N, list of N integers. Compute profit = 0. Set max_price = 0. Iterate from i = N-1 down to 0: if P[i] > max_price: max_price = P[i]; else: profit += max_price - P[i].
Implementation: Use sys.stdin.read or input() reading.
Now potential pitfalls: large N and prices up to 100000, profit could be large: up to N * (max_price - min_price) roughly 50000*99999 ≈ 5e9, fits in 64-bit signed (2^63-1 ≈ 9e18). Use Python int unlimited.
Thus code is simple.
But wait: The problem statement says "buy one share of M&M, sell any number of shares of M&M that you own". That means on a day you can either buy (exactly one) or sell any number or do nothing. So you cannot both buy and sell on same day? The description: "Each day, you can either buy one share of M&M, sell any number of shares of M&M that you own, or not make any transaction at all." So it's exclusive: either buy one, or sell (any number), or nothing. So cannot both buy and sell on the same day. But the algorithm described does not conflict: If there is a day with high price, you would want to sell all your shares; you would not buy that day because buying at a high price is not beneficial unless there's an even higher future price. The algorithm essentially buys on days with low price relative to future max, and sells on the day when that max occurs (but note that max could occur on multiple days? The algorithm as described might assume selling on the maximum day, but if the maximum appears on multiple days, you could sell on any of them. However, careful: The algorithm adds profit for a day if current price < max to the right. This implicitly assumes that you buy on that day and later sell at the day where the maximum price occurs (the first occurrence from the right? Actually, if there are multiple days with same max, you can sell on any. The algorithm just calculates difference, but it also treats future max as a single day. But the algorithm's correctness is standard; it's known as the "stock maximize" solution.
But one nuance: Since you can only buy one share per day, the number of shares you can buy is at most N. So total profit is sum of differences. The algorithm effectively buys on every day where price is less than some future maximum. But is it always optimal to buy on all such days? Consider scenario where there is a sequence: [2,5,2,5]. The algorithm: from right, max=5 (last), i=3 price=5 = max? if update max, stays 5; i=2 price=2<5 => profit+=3; i=1 price=5? 5<5 false (if we don't update on equal, but we might update). Suppose we do: start max=5 at i=3. i=2: price=2<5 => profit+=3. i=1: price=5 >= max => update max=5 (or not). i=0: price=2<5 => profit+=3. Total profit=6. But is it possible to achieve 6? Strategy: Buy day0 at 2, buy day2 at 2, sell both on day3 at 5: profit (5-2)*2=6. Also you could also buy day1? day1 price 5, no profit. So profit 6. But what about selling on day1? If you buy day0 at 2 and sell on day1 at 5, profit 3; then you can buy day2 at 2 and sell day3 at 5, profit 3; total 6 as well. So it's fine.
But could there be a scenario where buying on all days with price < future max is not optimal because selling on the max day might conflict with the one-share-per-day buying limit? Actually, you can buy at most one per day, but you can sell any number. So buying on many days is fine, you accumulate shares. Then you sell them all at some high price days. However, if there are multiple high price days, you might want to sell some shares earlier to free up capital? But capital is not constrained; you can buy unlimited shares as long as you have money? But we assume you have unlimited borrowing capacity? In typical problem, they consider profit as net gain ignoring capital constraints. But if you have to pay for purchases, you might need to have enough money from earlier sales to cover later purchases. However, the problem is classic and the solution assumes you can make transactions irrespective of cash flow because profit is net, and they don't require you to have non-negative cash balance. In these competitive programming problems, they assume you have infinite starting capital, and profit is just sum(sell) - sum(buy). So no constraint.
But let's double-check: The problem says "What is the maximum profit you can obtain with an optimum trading strategy?" Usually they consider net profit as final amount of money you have minus initial amount (which may be zero). And you start with zero shares and zero cash? Actually typical problem: you start with no money? Or you start with some initial? Usually we start with zero shares and sufficient money to buy shares, but they treat profit as total sales - total purchases, which is the net gain. So it's fine.
Thus the algorithm is correct.
Now, let's code. But note: There might be a twist: The problem statement says "buy one share of M&M, sell any number of shares of M&M that you own, or not make any transaction at all." That indicates that on a day, you cannot both buy and sell. So if you want to sell and then buy on the same day, you cannot. But the algorithm we described does not require that. For instance, in the scenario where you want to sell on a high price day and also buy on that same day (maybe because the price will go even higher later), that would be disallowed. But does optimal strategy ever require buying and selling on same day? If the price on that day is high, you would not want to buy, because you could buy earlier or later. If you want to sell on a day and then buy later the same day? Not allowed because you can only do one operation. However, could there be a situation where the optimal strategy involves selling some shares and also buying one share on the same day? Possibly if the price is a local minimum and also you want to sell some shares bought earlier that you didn't sell yet because there was a higher price later? But if you sell on a day, you are selling at that price; if the price is also a good buying opportunity (future higher price), you'd want to buy, but you cannot do both. You might decide to either sell or buy. But perhaps it's beneficial to sell earlier at a lower price to buy at a lower price? That seems counterproductive. Typically, you would not want to sell at a price that is lower than a future peak, unless you need to free up cash to buy more shares? But with unlimited capital, you don't need to sell to buy; you can always borrow. So no need to sell and buy on same day.
But could there be a scenario where you have shares bought at a low price and you anticipate a moderate price soon, and then a very high price later, but you want to sell some shares at the moderate price to then buy more at that same moderate price? That would be pointless because buying and selling at same price yields zero profit, but you might want to delay selling? Not needed.
Thus it's safe.
However, there is known alternative problem where you can buy any number but only sell one per day etc. This one is standard.
Now, we need to output the maximum profit.
Implementation steps:
- Read integer T.
- For each test case:
- Read integer N (but careful: input may have blank lines? Usually just lines)
- Read line with N integers.
- Convert to list of ints.
- Initialize max_price = 0, profit = 0.
- For i from N-1 downto 0:
if prices[i] > max_price:
max_price = prices[i]
else:
profit += max_price - prices[i]
- Print profit.
But we must ensure that we are correctly handling the case when max_price is 0 initially. Since all prices are >=1, it's okay.
But what if N is large? O(N) per test case is fine.
Time complexity O(T*N).
Now test with sample:
Test case 1: [5,3,2]
From right: max=2, i=2 price=2 -> price > max? 2 > 2? No (equal), but we use > to update, else add profit? But if we don't update, max=2, price=2, not greater, else: profit += max - price = 0. Actually profit unchanged. i=1 price=3 > max(2)? yes, update max=3. i=0 price=5 > max(3)? yes, update max=5. profit=0.
Test case 2: [1,2,100]
From right: max=100, i=2 price=100: >max? 100>100? No (equal), else: add 0. i=1 price=2 < max => profit+=98, max stays 100. i=0 price=1 < max => profit+=99. total=197. OK.
Test case 3: [1,3,1,2]
From right: max=2, i=3 price=2: >max? no (equal) profit+=0. i=2 price=1 < max => profit+=1, max remains 2. i=1 price=3 > max? yes, update max=3. i=0 price=1 < max => profit+=2, total=3. OK.
Thus matches.
Potential issue: We must ensure we are not misreading input. Use sys.stdin.read to read all ints, then process sequentially. Or use input() lines.
Given constraints, it's fine.
Now code in Python.
We'll write:
import sys
def main():
data = sys.stdin.read().strip().split()
if not data:
return
it = iter(data)
t = int(next(it))
out_lines = []
for _ in range(t):
n = int(next(it))
prices = [int(next(it)) for __ in range(n)]
profit = 0
max_price = 0
for price in reversed(prices):
if price > max_price:
max_price = price
else:
profit += max_price - price
out_lines.append(str(profit))
sys.stdout.write("\n".join(out_lines))
if name == "main":
main()
That's it.
But before finalizing, I want to double-check if there's any nuance about "sell any number of shares" meaning you can only sell if you own at least one, but we can always buy and hold. The algorithm implicitly sells at the maximum price day, but if there are multiple maxima, we might need to sell on multiple days? Actually the algorithm's profit sum (max_future - price) corresponds to buying on day i and selling on the day when the future maximum occurs. If there are multiple days with same maximum value after i, you could sell on any; but if the maximum occurs on a day that is not the last occurrence? Suppose the maximum price appears on day j, but then later there is a day k > j with lower price. The algorithm, when scanning from right, sets max_price to the highest price seen so far. So for day i < j, the max_price will be the maximum among days i+1...N-1. If the maximum appears at j, and later prices are lower, then max_price will be the price at j when scanning from right? Actually scanning from right, we first encounter the last day; if last day is not max, then as we go left we eventually encounter the max at j; at that point, max_price becomes that max. Then for days left of j, max_price remains that max (since it's the highest seen). So for day i < j, we use that max. This corresponds to selling on day j. That's okay. For days between j and the end? For days between j+1 and N-1 (i.e., after j), we have max_price being the max of days to the right, which might be lower than the max at j, but since we are scanning from right, for those days, when we encounter them (they are to the right of j), we had not yet seen j? Actually scanning from right: we start at N-1; if N-1 is not max, we set max_price = p[N-1]. Then we go to N-2, and so on. When we encounter day j, which is the maximum, we update max_price to that price. Then for days left of j, we use that max. So for days after j (i.e., indices > j), we processed them before encountering j; for those days, max_price was the maximum among days to the right of them (which might be lower than p[j]), but since those days are to the right of j, they would not be considered for buying if they are before j? Wait, those days are after j, so they are in the future relative to j. For day i < j, the future includes days after i, including j and later. When scanning from right, we treat all days as potential "future" relative to earlier days. So for day i < j, we consider the max among all days > i. That includes j. Since we eventually see j and update max_price to p[j], and then when we process day i (< j) later (since we go left), we have max_price = p[j] (or higher). So that's fine. For days after j (i > j), when we process them (from right), we haven't yet encountered j if we are moving leftwards? Actually scanning from right, we start at N-1, then N-2, ... eventually we reach j+1, then j. So for days after j (i > j), when we process them, j is to the left (not yet seen), but we need to consider the maximum to the right of those days, which does not include j because j is before them? Wait, for day i > j, the "future" days are those with index > i. Since j < i, j is in the past relative to day i, not in the future. So when we process day i, we should consider the maximum among days with index > i, which does not include j. So that's correct: we should not consider j as a selling day for day i if i > j. And our scanning algorithm does that: when we are at day i > j, we haven't yet seen j (since j is to the left), so the max_price we have is the maximum among days processed so far, which are indices > i. That correctly excludes j. So algorithm works.
Now, consider scenario where there are multiple peaks, and you might want to sell some shares at an earlier peak and then buy later before a later peak. The algorithm automatically accounts for this by buying on days where price is less than some future maximum, even if there is an earlier higher maximum but later higher? Actually it ensures that you buy on days where price is less than the maximum among future days. That is optimal. Because any share bought on a day i can be sold at the best future price. However, if you sell at an earlier peak, you could also re-buy later at a lower price before a later peak. But would that yield extra profit beyond simply holding until the later peak? Let's test: Suppose prices: [2,5,3,6]. Simple algorithm: from right, max=6; i=3 price=6 -> update max=6; i=2 price=3<6 -> profit+=3; i=1 price=5<6 -> profit+=1; i=0 price=2<6 -> profit+=4; total=8. Strategy: Buy day0 at 2, day1 at 5, day2 at 3. Then sell all on day3 at 6: profit = (6-2)+(6-5)+(6-3)=4+1+3=8. Could there be a better strategy that sells day1's share at day1? If you sell day1's share at day1 (price 5) and then buy again at day2 (3) and sell at day3 (6), you would: buy day0(2), buy day1(5), sell day1's share at day1? But you can't buy and sell on same day. So you could: day0 buy at 2, day1: you could either buy or sell. If you sell day0's share at day1 (5) profit 3; then you could also buy a share at day1? Can't do both. So maybe: day0 buy, day1 sell (profit 3). Then day2 buy, day3 sell (profit 3). Total 6. Not better. If you hold day0 share until day3, profit 4. So 8 is optimal.
What about a scenario: [2,4,3,4]. Algorithm: from right, max=4 (last), i=3 price=4 -> update? keep? Not add. i=2 price=3<4 -> profit+=1; i=1 price=4? if 4>=max? update max=4; i=0 price=2<4 -> profit+=2; total=3. Strategy: Buy day0 at 2, day2 at 3, sell both on day3 at 4: profit=2+1=3. Could we do: buy day0 at 2, sell at day1 (4) profit 2; then buy day2 at 3, sell at day3 (4) profit 1; total 3 same. So fine.
Now consider scenario where there is a dip after a peak and you could sell at the peak and then buy at the dip and sell later. The algorithm would buy at the dip (since it's lower than later max) and also buy before the peak? Actually if you hold shares bought before the peak, you could sell at the peak or hold to later. But if you sell at the peak, you get profit. But then you can buy at the dip and sell later. The algorithm's profit sum includes both: buying before the peak (if price before peak < peak, but also if later max > peak? Actually if later max > peak, then the maximum future price from before the peak is the later max, not the peak. So algorithm would not sell at the peak; it would assume you hold until later max. But what if you sell at the peak, then buy at dip, and sell at later max? That could yield more profit than holding through the peak? Let's analyze: Suppose prices: [1, 10, 5, 20]. The algorithm: from right, max=20; i=3 price=20 -> update max=20; i=2 price=5<20 -> profit+=15; i=1 price=10<20 -> profit+=10; i=0 price=1<20 -> profit+=19; total=44. Strategy: Buy day0, day1, day2, sell all on day3: profits (20-1)+(20-10)+(20-5)=19+10+15=44. Alternative: Sell day0 and day1 shares at day1 (peak 10): profit (10-1)+(10-10)=9+0=9. Then buy day2 at 5, sell at day3 (20) profit 15. Total 24. That's worse. What about selling only day1 share at peak and hold day0? If you hold day0 until day3 (profit 19), sell day1 at peak (0), buy day2 at 5 sell day3 (15) -> total 34, still less. So holding is better.
What about scenario: [3,8,5,6,7]? Here peak 8, later max? The maximum future from day0 is max(8,5,6,7)=8? Actually from day0, future includes day1=8, day2=5, day3=6, day4=7, max=8. So algorithm would for day0: profit += (8-3)=5. For day1: price 8, update max? when scanning from right: start max=7, i=4 price=7 => max=7? Actually let's compute algorithm properly: scanning from right: max=0; i=4 price=7 >0 => max=7; i=3 price=6<7 => profit+=1; i=2 price=5<7 => profit+=2; i=1 price=8>7 => max=8; i=0 price=3<8 => profit+=5; total=8. So algorithm says total profit 8. Let's see if we can do better: Buy day0 at 3, day2 at 5, day3 at 6, day4? Actually you can only buy one per day. So you could buy day0, day2, day3? But day4 you could also buy but selling later? Let's enumerate possible strategies: Option 1: buy day0, day2, day3 (or day4?), sell all on day1? But day1 is before day2, you cannot sell future shares. So you could only sell shares you already own. So if you buy day0, you could sell at day1 at 8. That gives profit 5. Then you could buy day2 at 5, day3 at 6, and sell at day4? day4 price 7. So profit from day2: 7-5=2, day3: 7-6=1, total 5+2+1=8. Alternatively, buy day0, day2, day3 and sell all on day4: (7-3)+(7-5)+(7-6)=4+2+1=7. Not as good. Or buy day0 and hold to day4: 4 profit only. So best is 8. So algorithm is optimal.
But is there any scenario where selling at an earlier peak yields more because you can use the proceeds to buy more shares later? However, you are limited to buying one share per day, regardless of cash. Cash does not constrain the number of shares you can buy, because you can always borrow. So no.
Thus algorithm stands.
Now potential twist: The problem statement might be from Hackerearth or similar and might require handling large input. We'll use fast I/O.
Edge Cases:
-
All prices increasing: e.g., [1,2,3,4,5]. Algorithm: from right, max=5; i=4 price=5 update max; i=3 price=4<5 profit+=1; i=2 price=3<5 profit+=2; i=1 price=2<5 profit+=3; i=0 price=1<5 profit+=4; total=10. Is that correct? You can buy each day and sell all on last day: (5-1)+(5-2)+(5-3)+(5-4) = 4+3+2+1 =10. Yes.
-
All decreasing: [5,4,3,2,1]. From right: max=1; i=4 price=1 update max=1? Actually start max=0, price=1>0 update max=1; i=3 price=2>1? 2>1 update max=2; i=2 price=3>2 update max=3; i=1 price=4>3 update max=4; i=0 price=5>4 update max=5; profit never added. Profit=0. Correct.
-
Flat: [5,5,5]. From right: max=5; i=2 price=5 no profit; i=1 price=5 >= max maybe update if >; profit none; i=0 same. profit=0. Good.
Now confirm large values.
Thus solution is final.
Now let's produce final answer with code. We'll also add some comments.
But before finalizing, I want to double-check the sample: Provided sample output matches.
Now there is also a known variation where you can buy at most one share per day but you can also sell any number, but you cannot hold more than one share? No, that would be different.
Alright.
Now write final code. ```python
import sys
def solve() -> None:
data = sys.stdin.buffer.read().split()
if not data:
return
it = iter(data)
t = int(next(it))
out = []
for _ in range(t):
n = int(next(it))
prices = [int(next(it)) for _ in range(n)]
profit = 0
max_price = 0
# traverse from the last day to the first
for price in reversed(prices):
if price > max_price:
max_price = price
else:
profit += max_price - price
out.append(str(profit))
sys.stdout.write("\n".join(out))
if name == "main":
solve()