All About the Money


If you're viewing this on the Challenge Zone website, you can click here to open the challenge in a new tab.

Scenario

Suppose you have an array for which the m element is the price of a given stock on the n day. Since you are a relatively new investor and stock trader, you want to take things slowly when you buy and sell shares of a stock. In other words, you only complete one transaction (i.e: you buy and sell one share of a stock) on a given day.

Task

Your task is to write a function optimizedProfit which finds the max profit of your transaction. Your function should accept an input of type Array that contains prices for a stock. The function is expected to return an Integer which is the max profit of your transaction.

Note/Tips: you cannot sell a stock before you buy one. Also, your selling price should be larger than your buying price in order to achieve the max profit possible!


optimizedProfit

The optimizedProfit function should accept an Array arguement and return an Integer value.


Sample Results

optimizedProfit([7, 1, 5, 3, 6, 4]) // --> 5 optimizedProfit([7, 6, 4, 3, 1]) // --> 0 (No profit was made 😭 ) optimizedProfit([2, 0, 8, 3, 11, 2]) // --> 11 optimizedProfit([12, 19, 7, 30, 22, 5]) // --> 23

Explanation

  1. In the first example, you buy the stock on day 2 where the price = $1 and sell it on day 5 where the price = $6, therefore your max profit equates to: $6 - $1 = $5.
    Note: $7 - $1 = $6 wouldn’t work because your selling price should be larger than your buying price as previously mentioned!
  2. In the second example, no transaction would would result in a max profit since the stock prices gradually decrease. In other words, all buying prices would be larger than all selling prices, which means no profit whatsoever!! :(

Your function should work for any Array argument. DO NOT HARDCODE!