DEV Community


Write better code: Day 1 - Apple Stock Prices

Arjun Rajkumar
Ruby, JS
・Updated on ・1 min read

This post originally appeared on Arjun Rajkumar's blog. Arjun is a web developer based in Bangalore, India.


I'm going to spend 1-2 hours/day solving different algorithms. More about this here.

Day 1: Question 1

Write an efficient method that takes stock_prices and returns the best profit you could have made from one purchase and one sale of one share of Apple stock yesterday.

For example:

  stock_prices = [10, 7, 5, 8, 11, 9]

# returns 6 (buying for $5 and selling for $11)

No "shorting"β€”you need to buy before you can sell. Also, you can't buy and sell in the same time stepβ€”at least 1 minute has to pass.

Question from InterviewCake

If you want to follow along, feel free to post your answers below.

Discussion (2)

arjunrajkumar profile image
Arjun Rajkumar Author • Edited

This was my logic for doing this.


  • Go thru each price one by one.
  • See if the current stock is lesser than previous min_stock stored variable.
  • See if the profit is greater than max profit stored. (max_profit, pot_profit)
  • Going thru the loop once so it is O[n] time
  • O[1] space as storing fixed.

It works with these few example cases:
Examples: [10, 7, 5, 8, 11, 9] -> 6 ; [10, 7, 100, 8, 11, 9] -> 92 ; [10] -> 0 ; [10, 2] -> 0.

alt text


delbetu profile image
M Bellucci • Edited

In ruby

possible_trades = stock_prices.combination(2).to_a
max_trade_index = { |x,y| y-x }.each_with_index.max[1]
return possible_trades[max_trade_index]
Forem Open with the Forem app