Puzzles / Riddles

2K

Solutions

2

Articles & Videos

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.

Share tech news, updates, or what's on your mind.

Sign up to Post

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) {
   // Your code here
}

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

Open in new window


The solution should have time complexity O(n).
2
Industry Leaders: We Want Your Opinion!
Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

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
}

Open in new window

2
 
LVL 6

Expert Comment

by:Brian Matis
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
 
LVL 9

Author Comment

by:James Bilous
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

2

Articles & Videos

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
>

No Top Experts for this time period. Answer questions to earn the title!