Stack Bash - Master data structures and algorithms

Buy and sell stock once

Easy
Let's say you're an ambitious stock trader.
But you only want to make one big trade in a given day.
You're given an array of stock prices, ordered by time. You can make one trade by buying at a particular price, and selling at another price.
Write a function that returns the max profit from one trade.
Note that you can't buy and sell a stock on the same day.
For example, given the input
[3, 1, 4, 5, 2, 9, 5, 3, 6]
Your function should return:
8 # Buy at 1, Sell at 9
You can do this in constant space.

Solution

6 Essential Arrays Coding Interview Problems

Master Arrays by trying the coding challenges below.
  1. 1.Trade stock onceEasy
  2. 2.AdditionEasy
  3. 3.Find the smallestEasy
  4. 4.Reorganize numbersHard
  5. 5.Maximum subarrayHard
  6. 6.Container of waterHard

Want to confidently pass your next coding interview?

Stack Bash helps new and veteran software engineers master data structures and algorithms for technical interviews.