Monthly Archives: February 2016

Given 12 coins, find one that is lighter or heavier

This is a problem of a well-known type: you’re given some coins (balls, rings), one of them is lighter, heavier, or maybe it can be either lighter or heavier. You need to find that one using no more than some specified number of weighings. In this particular example we have 12 coins, one of them is forged and may be heavier or lighter, we don’t known which. We need to find it in no more than 3 weighings.

In simpler problems, like when you’re given 8 balls and one of them is heavier, and we’re limited to two weighings, we can often succeed using brute-force approach. Try splitting them 4/4, then you quickly figure out that you can’t find one among 4 in one weighing. Well, just try a 3/3 split and then you’re done.

With 12 coins it is not so simple. You could guess that 4/4/4 first split is a good idea, but then you could spend hours trying to figure out the rest. So a smarter approach would be useful. And this is exactly what I’m about to show. But first let’s think about bounds.

Lower bound of the number of weighings

What is the lower bound of the number of weighings for this problem? There are 12 possible answers and each weighing gives us one of the three possible results. This leads to a ternary decision tree that represents our algorithm. To minimize the number of weighings we should minimize the height of the tree by balancing it out. The height of such tree is \lceil \log_3 12 \rceil=3. Makes sense. But only we assume that our algorithm only tells us which coin is forged without actually determining whether it’s lighter or heavier. Such an algorithm is hard to imagine, and if it gives us the complete answer, then there are total of 24 answers. Not that it changes the lower bound, though, as \lceil \log_3 24 \rceil is also 3.

Note that it is only a lower bound. It may or may not be actually reachable, and that’s much harder to prove (but the proof does exist with exact numbers). Obviously if we can find an algorithm that works, then it’s reachable. But if we can’t find one, it doesn’t mean that it doesn’t exist. Unless we’ve actually brute-forcibly tried all of them. It isn’t that hard for small problems, and I’ve actually done it for 12 and 13 coins. Turns out the lower bound is reachable in case of 12 coins, but in case of 13 coins it’s only reachable if we don’t need to know whether the forged coin is lighter or heavier. So even though that \lceil \log_3 26 \rceil = 3, we can’t build an algorithm that finds all 26 answers.

A heuristics for building the right solution

How do we produce an algorithm for a given problem without brute-forcing it? I hereby present a heuristics that gives three hints as to what to do next.

U -> L, H, G; L -> G; H -> G

Possible coin transitions

Let’s start by partitioning coins into four groups. Initially all coins belong to the group U, which is the group of coins we know nothing of. Then there are groups L and H which contain coins that may be lighter (but not heavier) and vice versa. If we weigh some coins from U and they don’t balance out, then the heavier pile goes to H and the lighter one goes to L. The rest of the coins, which did not participate in the weighing, are obviously genuine so they go to the last group, G. When we weigh suspicious coins with some genuine ones and they balance out, then the suspicious coins go to G no matter which group they belonged to.

Our goal is to maximize the information gained by each weighing. And since we have no idea what the result of the weighing will be, we should try to maximize worst-case results, much like in the minimax algorithm.

But how do we measure information gained? Obviously each coin promoted from one group to another is something. But if a coin jumps from U to G directly, it’s even better than a coin going from U to L or H, or from L or H to G. So here is the first hint:

We should pick a weighing that maximizes the minimum of N_{U \rightarrow L} + N_{U \rightarrow H} + N_{L \rightarrow G} + N_{H \rightarrow G} + 2N_{U \rightarrow G} for all possible results of a weighing. In other words, each coin jumping from U to G gives us two points, and all other movements give us one points each.

The second hint is somewhat obvious. Whenever you’re facing a weighing that may only give you two results instead of the three (e. g. it’s impossible for the coins to balance out), you’re probably doing something wrong, unless it’s the last weighing.

The third hint is less obvious: if, at some point, you hit a decision tree branch that allows you to figure out the answer in less weighings than the given limit, you’re probably doing something wrong.

The last two hints are actually the two sides of the same coin, no pun intended: they both tell you that you’re going to create an unbalanced decision tree. In a well-balanced ternary tree most non-leaf nodes should have all three children, and the tree should ideally have the same height everywhere. Of course, that depends on the exact problem: if you’re allowed to do 100 weighings for 12 coins, you probably end up with lots of branches much shorter than that. But for three weighings it’s really desirable to balance everything out.

The last two hints are mostly redundant. If you’re squeezing as much information as possible, you would probably create a well-balanced tree anyway. So they just serve as additional warnings. But sometimes they simplify the math.

Back to the problem

So let’s try to build a good algorithm for 12 coins and 3 weighings. A 6/6 split is a bad idea because of the second hint. That’s how it simplifies the math, so we can instantly skip to an n/n split, where n<6. Since the situation is symmetrical for now, we don’t need to consider lighter/heavier results separately, so that leaves us two possible results of the weighing:

  1. The chosen coins balance out, therefore jumping right to G. The rest still belongs to U. That gives us 4n points (2n coins jumping from U to G).
  2. They don’t balance out. Therefore the lighter group goes to L, the heavier one to H and the rest straight to G because we know that the forged coin is among the weighed piles. That gives us 2n+2(12−2n) = 24−2n points.

The first expression increases with n, the second one decreases. If we find the point where they are equal, it’s obvious that the minimum will be less towards both directions from there: to the left 4n will be less, to the right 24−2n will be less. That gives us the following equation:

4n = 24−2n, 6n = 24, n = 4

Then we have two cases to consider.

Four coin piles balance out

The easiest case is when the coins balance out, so we now have just 4 U-coins. Intuitively, one may think of comparing two of them. If they balance out, we compare one of them with one of the remaining ones. If they balance out again, then the remaining one must be the forged one, but we don’t know whether it’s lighter or heavier. If the third weighing doesn’t balance out, then the third coin is the forged one (and we now know whether it’s lighter or heavier). If the second weighing doesn’t balance out, then we again compare one of them with one of the remaining ones, this time identifying not only which one is forged, but also whether it’s heavier or lighter. But there was still one case when we couldn’t do it. So let’s try to use our heuristics.

It makes no sense to compare good coins with good coins, so the only way we may end up putting good coins on the balance scale is to compare them with suspicious ones. This means that only one pan should contain good coins (if both of them do, we can just remove the minimum number of good coins from both pans). That means that we can have n1 U-coins on the left pan and n2 U-coins and n1-n2 G-coins on the right pan. Here, n2 can be zero (comparing suspicious coins with good ones), but then n1 can’t be 4 because all 4 U-coins can’t possibly balance out with 4 G-coins, and the second hint tells us it’s probably a bad thing. n1+n2 also can’t be 4 because of the same reason. So we have three cases now:

  1. Balancing out: 2(n1+n2) points for coins now promoted to G.
  2. The left side is lighter: n1+n2 points for promoting n1 coins to L and n2 coins to H. 2(4−n1−n2) points for promoting the rest to G.
  3. The left side is heavier: n1+n2 points for promoting n2 coins to L and n1 coins to H. 2(4−n1−n2) points for promoting the rest to G.

Note that even though cases 2 and 3 give equal number of points, the resulting group configuration is different if n1 ≠ n2. Now let n=n1+n2, then we have the following equation:

2n = 2(4-n), 3n = 8, n = 2 2/3

Let’s pick the closest integer value n = 3. Note that n1 and n2 by themselves don’t really matter, so let’s pick n1=3, n2=0. Going back to three cases:

  1. Balancing out: three coins are genuine, which means the remaining one is forged. We even have a spare weighing to determine if it’s lighter or heavier. Here is where 13 coins case breaks (the algorithm up to this point is the same): we can still determine which one of the remaining coins is forged, but with probability 1/2 we won’t know whether it’s lighter or heavier.
  2. Three U-coins are lighter: it means that the forged coin is among them and it’s lighter. Comparing any two of them will give us the answer.
  3. Three U-coins are heavier: the same as case 2, but the forged coin must be heavier.

See how using our heuristics allowed us to build a much simple algorithm than one may come up with intuitively, and how it’s also more powerful?

Four coins do not balance out

This case is much harder because we now have 4 L-coins, 4 H-coins and 4 G-coins which is a mess of possible combinations. Let’s pick n1 L-coins and m1 H-coins for the left pan, and n2 L-coins and m2 H-coins for the right pan, possibly adding some n1+m1−n2−m2 G-coins. Obviously we can’t use all L and H coins or else we can’t possibly balance out everything. The three cases now are:

  1. Balancing out: n1+m1+n2+m2 points for new G-coins.
  2. Pan 1 is lighter: m1+n2 points plus 8−n1−m1−n2−m2 points for not-participating coins. Where did m1+n2 points came from? Well, m1 coins were from H-group and now they are on the lighter side. The forged coin can’t possibly be both heavier and lighter, so it’s obviously then that these m1 coins are all genuine. Ditto with n2.
  3. Pan 1 is heavier: m2+n1+8−n1−m1−n2−m2. The same reasoning.

We now have three expressions and must do our best to balance them out. Let’s put it this way:



Subtracting one from another we get m1+n2=m2+n1. Let k denote this, that turns the first expression into 2k and the second and the third ones into 8-k. By solving 2k=8-k we get 3k = 8, much like in the previous case. And again, we have some freedom, but we can’t pick n1=3, m1=0, n2=3, m2=0, for example, because n1+n2=6 and we only have 4 L-coins. So let’s pick n1=3, m1=2, n2=1, m2=0. We’ll also need to add all 4 genuine coins to the right pan.

  1. Balancing out: we’re now left with 2 H-coins. Finding out which one is forged is a piece of cake.
  2. The left pan is lighter: we’re left with 3 L-coins. The right pan did not contain any H-coins, so it’s obviously that the forged one is among those 3. Again, it’s trivial to solve.
  3. The left pan is heavier: we’re left with 2 H-coins from the left side an 1 L-coin from the right side. Comparing the two H-coins we will instantly know which one of them is heavier and therefore is the forged one, in case they don’t balance out. If they do, then the forged one must be the remaining L-coin.

Problem solved! We didn’t even have to try different variations (but you can, and you’ll get correct algorithms). And we also didn’t have to use the third hint.

Encodings, Unicode and broken code

This is another sad tale of character encodings. Consider this LeetCode problem that asks to check whether the given strings are isomorphic. Isomorphic strings being defined as strings of the same length with a bijection mapping between the characters. For example, “aba” is isomorphic to “ava” with mapping a \leftrightarrow a, b \leftrightarrow v and “mlm” with mapping a \leftrightarrow m, b \leftrightarrow l, but not to “aaa” (no bijection since both “a” and “b” are mapped to “a”).

Now consider possible solutions in Java. One obvious solution:

Runs in 36 ms, certainly not the fastest submission. One way to “optimize” it:

This runs in 12 ms. Three times faster! Beating 92%! And here is yet another version:

Now, let me ask a question: which of the solutions above is the best one?

The last one is something an English speaker with C background might come up with. It will obviously break for any characters outside US-ASCII, including Cyrillic, Chinese, Hebrew or even German or Irish (because of the umlauts and fada). So obviously it’s not acceptable.

The second one is trickier. One thing is that it might break if one of the strings contains NUL characters because we abuse NUL as the “character not mapped” special value. Another thing is that initializing the whole array with zeroes takes \mathcal{O}(65536) time which could make it a poor choice for short strings.

So it looks like the first one is the best, right? It scales nice to any lengths, and even though it’s slower, it handles NULs properly.

Well, the answer is: all of them are wrong! One test case that none of the solutions above will pass is “ab”, “冬b”. In case you can’t see it, here is a picture:


That’s right, that one weird Chinese character is enough to break all of the solutions above. Moreover, it breaks LeetCode testing system as well (just like Cyrillic or anything non-ASCII does) and LeetCode Discuss forums too (unlike Cyrillic and many other non-ASCII symbols). Why? What’s wrong with that particular character? Java stores strings using Unicode, right? That’s why char is two bytes, after all! So it should be able to handle any characters without any problems! The dark age of terrible national encodings is over!

In order to understand it, we must look back at the history of encodings and Uncode.

It all started in 1960s or even long before that (Morse code came into existence long before the first computer). But it’s in 1960s that all hell broke loose. In 1963 both ASCII and EBCDIC were introduced. While even EBCDIC is apparently still in use today, it’s ASCII that became widespread, and the fact that ASCII was a 7-bit encoding meant that there was one “free” bit and 128 unused codes in the 128-255 range. That, and the lack of any letters except basic Latin, immediately gave birth to a myriad of various national encodings. Worse, multiple encodings were sometimes used for the same languages. I know of four Russian, for example: code page 866 (“MS-DOS” encoding), code page 1251 (”Windows” or ANSI encoding), KOI8-R (a really weird encoding that arranges letter according to English alphabet, not Russian one, was really widespread in the early days of Russian Internet) and the “standard” ISO-8859-5 that was rarely used at all. This is still a major source of various troubles, as when you run a program in a console window, you have no idea which encoding will be used and therefore you have about 50% chance of getting garbage (less in practice because most programs will use the MS-DOS encoding). And nobody plans to fix it because it is impossible and because nobody cares about console windows nowadays.

Chinese and Japanese people got it even worse: 128 values are obviously not enough to represent about 2000 ideographs in Japanese (and that’s only a subset of Chinese!), so they went ahead and invented two-byte encodings, which made things much worse because now, having some bytes, you couldn’t even determine the string length if you had no idea which encoding is used.

Then Unicode came into being. The first standard was published in 1991 and it introduced a 16-bit encoding intended for universal use, which included all characters deemed reasonable. Unfortunately, the bunch of Old Evil Encodings didn’t disappear at the very same moment, so the only thing that really happened that day is that the world now had one more encoding to deal with. No, wait, make it two encodings because Unicode defined characters as 16-bit units, but those can be represented with bytes using either Little Endian or Big Endian order.

Even worse, Unicode apparently failed to consider some important characters like rarely used ideographs (like that 冬), even though they are a part of personal names and names of places. Imagine you can’t type your own name as you’re trying to use some software! So apparently some extension was needed. That is how Unicode transformed from a single 16-bit encoding into a whole standard of concepts and encodings.

The core concept is the code point. A code point is a 21-bit number corresponding to some character, typically represented as a 32-bit integer in memory and as something like U+00B0 in writing, where 00B0 is the hexadecimal of the code point (in this case it’s the degree sign: °). The current range for the code points is U+0000–U+10FFFF, hence 21 bit (but it’s extendable). So, you see, to say that Unicode is a 16-bit encoding is wrong in several ways: Unicode is a standard (defining multiple encodings), not an encoding, and not all Unicode encodings are 16-bit.

The code points defined in the first Unicode standard now belong to the so-called Basic Multilingual Plane (BMP), and that includes code points in the range U+0000–U+FFFF. That is Latin, English, Arabic, Hebrew, most Chinese and Japanese and lots of other useful things. However, there are some Chinese symbols outside the BMP, which belong to the so-called Supplementary Plane, and the code points U+10000 and above are called supplementary code points (or characters).

There are three main encodings in the current Unicode standard. By “main” I mean that they are both part of the standard and are widely used. These are:

  1. UTF-8, which is a variable width character encoding, where a code point can be represented by one to four bytes (to six bytes if we ever need code points above U+200000). Good thing about it is that NUL byte is only used to represent the NUL code point, so UTF-8 strings can be NUL-terminated. Another good thing is that ASCII characters are represented by single bytes identical to their ASCII representation.
  2. UTF-16, which is also (surprise!) a variable width character encoding, where a code point can be represented by one or two 16-bit code units (which, in turn, can be represented by two bytes using either BE or LE byte order, that makes UTF-16LE and UTF-16BE). BMP code points are represented by one code unit, supplementary code points are represented by the so-called surrogate pairs, which consist of the first (high) surrogate and the second (low) surrogate. The high/low concept doesn’t really have anything to do with byte ordering here, they encode higher and lower bits of the code point, and the high surrogate always comes first regardless of the byte order.
  3. UTF-32 is a fixed width character encoding where each code point is encoded as a single 32-bit number (which, again, makes it UTF-32LE or UTF-32BE depending on the byte order).

As you can see, UTF-16 is pretty messed up, and if you consider it a fixed-width character encoding, you may end up in trouble. In fact, when I finally figured out all this, I started to think that UTF-16 is outright evil: it doesn’t have the nice properties of UTF-8 (like NUL-termination and ASCII compatibility) and its only advantage over UTF-32 is lower memory consumption, but with modern amounts of RAM it shouldn’t be a real problem any more. And the fact that it’s a variable width encoding screwes up almost any text processing algorithm you can think of. Here is a correct solution for the mentioned LeetCode problem, for example.

It’s certainly not as efficient as the others, but it’s the one that really works (and no, you can’t say it works unless it handles all possible inputs correctly). Some useful String and Character methods include:

  • String.codePointCount: returns the number of code points between the specified indexes. This is the true length of the string (not the number returned by String.length).
  • String.offsetByCodePoints: “adds” two indexes together, when one index is a char index and another one is measured in code points, returning the resulting char index. For example, if you have the string “冬b”, then offsetByCodePoints(0, 1) would return 2 because “b” is located at index 2, not 1. A call to offsetByCodePoints(2, 1) would return 3 (the end of the string) because “b” is only a single code unit. This method is kind of reversed version of the previous one.
  • CharSequence.codePoints: returns an IntStream of code points.
  • Character.codePointAt, Character.codePointCount: same as the String method, only for character arrays.
  • Character.highSurrogate, Character.lowSurrogate: return the respective surrogate for a given code point.
  • Character.isHighSurrogate, Character.isLowSurrogate: for a given code unit, check whether it’s a part of a possible surrogate pair. This is very important method for many cases when you need to be able to distinguish surrogate pairs from BMP characters. For example, StringBuilder.reverse uses it to properly reverse a string contains surrogates (because they obviously don’t need to be reversed).

On top of that, many methods have two variants: one accepting a char, other accepting a code point. Those accepting chars should really be deprecated because they actually encourage writing buggy code.

Considering all that, we must conclude that while Unicode indeed made life much easier than it was in the Dark Ages, it must be handled properly unless we want to enter another dark age where a person may fail to register an account on some site simply because he happened to have a supplementary character. Or wait a minute. We have already entered it. Now we must get out, so we all better start writing bug-free code!

Best Time to Buy and Sell Stock IV

Another awesome problem on LeetCode deals with buying and selling stock. You are given a list of prices, are allowed to only open long positions and you must close one before opening a new one. This would be trivial (buy on low, sell on high), but you’re limited to a total of k buy/sell transaction pairs. You need to return the maximum profit.

At first I thought it was a dynamic programming problem. Quick peek at the tags confirmed that suspicion. I quickly realized that subproblems require to determine the maximum profit for d days, starting with 2 (can’t make a profit on one day because only one price per day is given). Moreover, it is quite obvious that we have to determine maximum profits for limited numbers of transactions in range 0..k. This requires only k memory because you only need the profits for the previous day to compute the tomorrow profits. You need to consider, though, that you may have left your position open, so some potential profit may exist. In this case you also have to record the opening price.

In the end it looked like this:

Not very elegant, but pretty straightforward. profitClosed[j] is the maximum profit that may be made by today with j buys/sells, while leaving no open position. profitOpen[j] is the same thing, but with open position and openPrice[j] denotes the best buying price so far, so we can instantly gain profitOpen[j] + current price − openPrice[j] by selling today. And that’s what we do, but only if the resulting profit is more than we could gain by performing less transaction. When we do it, the number of elements in the profitClosed array becomes greater than the number of elements in profitOpen, so we immediately open a new position on the next loop.

Then we update our profits in the inner loop. We re-close an open position if we can get a better profit and we reopen if we can get a better profit plus potential profit! That is important because that’s what an open position is about: if we can instantly get that much profit, it would be a waste to reopen at the current price even if we can get a better profit today, it will still bite us in the future.

This solution runs from 4 to 6 ms depending on the weather on Mars and the number of holes in the cheese. For example, replacing > profitClosed[lClosed] with > 0  in the pre-loop close-another-position condition speeds it up (branch prediction?) even though we open not very profitable positions.

There are much better solutions using the same idea. This one is particularly awesome, as it does both loops in just four lines.

However, I didn’t particularly like the DP idea here. It felt like this problem should have a better solution, so I kept on digging. After seeing this one, I decided to do the same thing in Java:

Not terribly concise, but pretty straightforward. The idea is that we calculate the profit that we’ll lose if we do nothing on a particular day, thus reducing the number of transactions. Then we keep on throwing away those days starting with those that give the least profit. Obviously throwing away days on monotonous intervals won’t affect the profit at all, so we don’t even add those to begin with. We are only interested in “peaks” and “valleys” (plus possibly the first and the last days).

Maybe replacing indices arrays with a linked list was a bad idea. It’s definitely worth to try arrays instead. As it is, it runs in 20 ms. Not so terribly efficient. But I don’t think switching to array will improve it that much because the main slowdown here is the tree. Even though I only add peak/valley days and do it only if transaction reduction is needed, it is still a pretty slow thing. And it still felt like not the totally right thing.

Then I saw this solution based on another one. And I must admin, it really took me a while to figure these out. Especially loop invariants. So I hereby present my own implementation of the same ideas that runs in 3 ms \mathcal{O}(n) (if we assume quickselect is linear, which is a fair assumption since randomization provides a very high average case probability).

And here comes the explanation.


Consider this price chart. Let’s consider only closing prices (80 for the first day, 70 for the 2nd, 75 for the 3rd and so on). For a “bullish” day (green) the closing price is the top of the candle, for a “bearish” one it’s the bottom. If we were to aim for the maximum profit, we’d perform the following transactions:

  1. Days 2–6, prices 70–100, profit 30.
  2. Days 8–11, prices 50–80, profit 30.
  3. Days 13–17, prices 20–60, profit 40.
  4. Days 19–21, prices 40–50, profit 10.
  5. Days 23–27, prices 30–70, profit 40.
  6. Days 29–31, prices 10–100, profit 90.

The total profit is 30+30+40+10+40+90=240.

Now, we are limited to some number of transactions. If that’s only one, then the best we can get is the last transaction, that is, 90. If two, then the best is to buy on the 13th day, sell on the 27nd (profit 50), buy on the 29th and finally sell on the 31st for the total profit of 140. Note that the first transaction is not even among the list of transactions we’d perform if we weren’t limited. That is because the first three transactions (green runs on the chart) are best united into a single one. So we need to figure out which transactions to unite.

Consider the following problem. For given intervals [v1, p1], [v2, p2], v1 < p2, v2 < p2, where “v” stands for a valley and “p” for a peak, what are the possible relationships between them? There are six:

  1. They don’t overlap, and p1 ≤ v2. For example, days 13–15 and 15–17 with prices [20,40], [40,60].
  2. They don’t overlap, and v1 ≥ p2. For example, days 2–6 and 13–17 with prices [70,100], [20,60].
  3. They do overlap, and v2 < p1. For example, days 13–17 and 23–27 with prices [20,60], [30,70].
  4. They overlap, and v1 < p2. For example, days 2–6 and 8–11 with prices [70,100], [50,80].
  5. The second interval is fully included in the first one. For example, days 13–17 and 19–21 with prices [20,60], [40, 50].
  6. The first interval is fully included in the second one. For example, days 23–27 and 29–31 with prices [30,70], [10,100].

I’m not totally rigorous here about the strictly-less/less-than-or-equal thing. It doesn’t matter, though, because corner cases when something is equal to something else may be handled as either—they are kind of “at the border” between the two and belong to both sets. For example, if two transactions have exactly the same price range, then it doesn’t really matter whether you think of the second one included in the first one or vice versa. Or you may even want to consider them to be overlapping.

Now we need to ask ourselves a question: if we have two transactions and are allowed to make only one, how to get the maximum profit? Let’s consider all six cases.

Two transactions: both giving 20, both on the increasing interval

Case 1: transactions (1) and (2) are combined into (3)

The first case is not really possible for adjacent transactions if we only consider “peak—valley” transactions to begin with (the end of the second transaction is not really a peak, and the beginning of the second one is not a valley). Indeed, if two intervals form a monotonous non-decreasing sequence, then why bother splitting them in two intervals at all? However, for transactions far apart, this case is still possible (although not in our example). Anyway, in this case the answer is quite obvious: just combine two transactions into a single one, buying on for v1, selling for p2.

Case 2: one transaction gives 30, another 40, but it's way below the first one, so we can't combine them

Case 2: between transactions (1) and (2) we pick (2) because it’s more profitable

The second case is also obvious: just pick up the most profitable one. We can’t unite them because the starting price of the first one is greater than the selling price of the second one. If you buy on the 2nd day and sell on 17th, you’ll have 10 loss instead of any profit.

Two transactions overlap and the best profit is from the start of the first one to the very end of the second one

Case 3: two overlapping transactions (1) and (2) are transformed into one long transaction (3) and an imaginary short transaction (4)

The third case is the most tricky one! Since the lowest price is v1, and the highest price is p2, then the best is to combine them into a single transaction. This sounds like it increases the transaction count tremendously (as we have to consider all possible combinations), but in fact it doesn’t. We do a really amazing trick here: instead of considering them as two separate transactions to begin with, we instead think of them as one “long” transaction (buying at v1, selling at p2) and one “short” transaction (selling at p1 and buying later at v2), even though short transactions aren’t technically allowed by this problem! This works because we pick transactions starting with the ones giving us the most profit. In this case, the long one is guaranteed to give us more profit than the short one, so we’ll either pick the long one (without violating anything) or pick both. And since both transactions give us exactly the same profit as two long transactions we had to begin with (p1-v1+p2-v2=p2-v1+p1-v2), then it’d appear in the net result as if we performed two separate long transactions.

Two transactions overlap, but the combined one gives less profit

Case 4: between transactions (1) and (2) we choose the most profitable (in this case any of them) because the combined transaction (3) is the least profitable

The fourth case is trivial: since the combined transaction is the least profitable, we just pick the most profitable one of the two. In our example they are equally profitable, though.

Two transactions, the second one has higher valley and lower peak

Case 5: the second transaction is included in the first, so the first one gives the best profit we can get

The fifth case is even more boring: the first transaction has both the lowest price and the highest price, so we just pick the first one.

Two transactions, the second one has the lowest and the highest prices

Case 6: the second transaction gives the most profit

The sixth case is the mirror image of the fifth one. Just pick the second transaction.

So we have one case when we should combine transactions unconditionally, two cases when we should choose the most profitable of the two, two cases when the most profitable one is obvious and one tricky case when we transform two long transactions into one long and one imaginary short one. Now to the algorithm.

The algorithm preserves the following invariant. When an outer loop iteration finishes, the valleys/peaks stack contains transactions that are related according to case 5 above, with the latest transaction on the top. The invariant is obviously true at the beginning since the stack is empty, and any proposition is true for the elements of an empty set (all humans that have visited other galaxies have green ears—there are none at the moment of writing, so I’m not wrong in saying that “all” (zero) of them have green ears).

The invariant is preserved by these two loops:

The first loop just pops transactions with v1 > v2, which corresponds to cases 2, 4 and 6. In all these cases we don’t combine transactions, so it’s fine to just pop them and consider separately. The termination condition guarantees that v1 ≤ v2 at the end of that loop, assuming there are any elements left in the stack.

The second loop handles the tricky case 3. We pop a transaction, then generate a “short” transaction and put it into the profits array. Then we set the current valley to the one popped from the stack, so the current transaction now corresponds to the long one. Then we continue the loop because it may or may not be possible to combine it with the previous one and so on. Note that the termination condition guarantees that p1 > p2 at the end of the loop, assuming there are any elements left. Assuming the invariant held true at the start of the outer loop, popping some elements could not have increased the valley at the top of the stack because it may only decrease as we go deeper.

Note that we don’t consider case 1 separately. Instead, we treat it as a special subcase of case 3 where the “short” transaction gives us negative profit. Since we’re going to pick only the highest profits anyway, this is fine. One may think that it may have negative impact on the total profit in the case where k is high enough to allow all transactions to complete, but in fact it may not. This is because two adjacent transactions can’t form case 1 anyway, remember? So when we have transactions like this, it means that they are separated by some transactions in the middle. And if we’re going to pick every profitable transaction, then we can’t really combine those two because we aren’t allowed to engage in multiple transactions. So this negative profit corresponds to the profit loss caused by the fact that we need to sell first in order to buy again.

Lastly, since case 5 corresponds to the items in the stack, we pick top k profits using randomized quickselect and sum them up.

One last note before we get to the example: the loop may generate one false peak/valley pair at the end of the input array if the prices list ends with a valley. This corresponds to a zero-length transaction giving zero profit, so instead of checking for this corner case we can allocate one more element in the profits array to hold this zero. It won’t affect the result in any way.

Now let’s see how the algorithm works on our example. Our valleys/peaks are: 70–100, 50–80, 20–60, 40–50, 30–70, 10–100.

Step 1 (70–100). The stack is empty, so the inner loops don’t execute. The stack becomes (bottom-to-top)

Step 2 (50–80). The first loop pops the transaction because 70 > 50 (case 4). The stack becomes empty, therefore the second loop doesn’t execute. The next transaction is pushed into the stack.

Step 3 (20–60). The first loop pops because 50 > 20 (case 4). The rest is just like the previous step.

Step 4 (40–50). The first loop doesn’t work because 20 < 40. The second loop doesn’t work either because 60 > 50. Case 5.

Step 5 (30–70). The first loop pops only [40,50] because 40 > 30 (case 6), but 20 < 30. The second loop then transforms [20,60] and [30,70] into [60,30] (added to the profits) and [20,70] (becomes the current transaction). This is case 3.

Step 6 (10–100). The first loop pops because 20 > 10 (case 6). The second loop doesn’t work because the stack is now empty. The last transaction is pushed into the stack.

Lastly, we pop the stack and we now have

A total of six transactions! Now for the different values of k we have:

  1. Just pick up the last transaction.
  2. Pick up 50 and 90, where 50 corresponds to 20–70 produced on the 5th step (buy on the 13th, sell on the 27th).
  3. Pick up 50, 90 and any of the 30s, where 30s can be one of the first two transactions or the imaginary transaction that splits our 50 into 20–60 (days 13–17) and 30–70 (days 23-27), which gives 40+40 = 50+30.
  4. Pick up 50, 90 and any two of the 30s.
  5. Pick up 50, 90 and all of the 30s (meaning 50+30 now definitely means two real transactions 40+40).
  6. Pick all of them (the trivial unrestricted case).

Isn’t this awesome?