# Puzzles / Riddles

2K

Solutions

3K

Contributors

Puzzles and riddles are statements and questions framed such that they require ingenuity and imagination to resolve. Most are mathematical conundrums, but can also include the arcane, trivial or simply funny.

Here's an interesting coding puzzle:

A trader can perform two buys and two sells in a day of a given stock. An array of positive integers represents the share price of this stock at different times of the day (index i = 0 represents hour 1, i=1 represents hour 2, etc). The trader must always sell any current shares he has before he buys more shares. Write a function that determines the maximum profit the trader can make by buying and selling stock for a given day.

``````int maximizeProfit(int[] prices) {
}

ex:
[10, 22, 5, 75, 65, 80]
The maximum profit is 87: buy at 10 sell at 22, buy at 5, sell at 80.
``````

The solution should have time complexity O(n).
2
Here's an interesting brain teaser / programming puzzle I learned the other day. The answer can be achieved with a single line of code with computational complexity better then O(n).

N is a number that represents n boxes and n workers. All boxes are initially closed. Worker 1 goes through and toggles every box open. Worker 2 goes through and toggles every 2nd box (closed if open, open if closed). In the end, every worker i ⊂ N  has toggled every ith box opened or closed. Print the boxes that remain open at the end.

``````public void printOpenBoxes(n)
{
// Implementation here
}
``````
2

Expert Comment

Fascinating! So, I'm curious, though... Did you figure this out via the underlying math of the situation, or by doing it the hard way and noticing the pattern in the results?
0

Author Comment

I saw the answer before I could figure it out. I just thought that it was a good lesson that you should always consider a simpler version to a problem before you waste a bunch of time diving too deep into a solution that is over complicated
0

# Puzzles / Riddles

2K

Solutions

3K

Contributors

Puzzles and riddles are statements and questions framed such that they require ingenuity and imagination to resolve. Most are mathematical conundrums, but can also include the arcane, trivial or simply funny.

Top Experts In
Puzzles / Riddles
Monthly