Inspired by the following great articles/videos:

https://www.geeksforgeeks.org/maximum-profit-by-buying-and-selling-a-share-at-most-k-times/

https://www.youtube.com/watch?v=Pw6lrYANjz4 (algoexpert video)

Here is the solution runnable online:

https://paiza.io/projects/BIfLpKxnZbaEOIjIk9f9EQ?language=mysql

And here is the code gist:

The iterative solution is more difficult to come up with. The trick with iterative is that we need extra information in the stack entries. I used an extra bool flag to indicate whether we’ve handled (pushed) the nodes children. As we go around our loop we check whether the top stack entry has had its children handled and if not then we add the children (right first then left) to the stack and mark it that the children are handled. Otherwise if the top stack node has had its children handled already then we deal with this node, i.e. we add its value to the result vector and pop it from the stack. We have to use this handled children flag as we need to deal with the left children first and then leave the right children for later.

]]>s="aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaabaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" wordDict=["a","aa","aaa","aaaa","aaaaa","aaaaaa","aaaaaaa","aaaaaaaa","aaaaaaaaa","aaaaaaaaaa"]]]>

The O(n) solution relies on calculating from left to right to get increasing sequences, where we set candy[i] to 1 + previous one if rating[i] is bigger than previous rating. We do the same for right to left to get decreasing sequences. We then take the max of those two left and right results. There is also a O(n) time and O(1) space solution but that is more complicated.

Here is the source code for the brute force O(n^2) solution:

https://gist.github.com/adamkorg/6308ae6d8c7dfeb42d45c020022b9af3

And here is the code for the O(n) 2 vector solution:

https://gist.github.com/adamkorg/3bb831b738dd1b1658149d1580357b0d

And here is the code for the O(n) 1 vector solution:

The simple slow recursive solution:

https://gist.github.com/adamkorg/d743bd068ed0bdcff060d25e5f905ec0

Recursive with DP:

https://gist.github.com/adamkorg/a2a6079ae2c3f300ee99e98594b6252a

And below is the iterative DP solution: