Each day I solve several coding challenges and puzzles from Codr's ranked mode. The goal is to reach genius rank, along the way I explain how I solve them. You do not need any programming background to get started, and you will learn a ton of new and interesting things as you go.
Even though this challenge contains quite a lot of code, it's pretty easy to solve. We only need to fix the bugs 💧 and ☃️, so we don't even have to fully analyze & understand the code to complete it.
The first bug 💧 is easy since it's just the initial declaration of a variable, you can quickly skim through the code and you'll find that profit
is the only variable that hasn't been declared yet, so that must be it.
The last bug ☃️ appears to be a function call, because it provides an argument arr
, and the only function here is maxProfit
.
Now that we've solved it, let's take a moment to analyze what the code is doing. It starts with an array arr
, and then calls maxProfit(arr)
. If you look closely at the for-loop, it starts from index 1 (instead of 0), then the if-statement checks whether the previous value from the array is smaller than the current value; if it is then: profit = MathMax(profit, price - min)
. If it's not then min = MathMin(min, price)
. In a nutshell its computing the profit with some specific requirements that we don't know (but can analyze).
Join me on the Road to Genius and upgrade your programming skills, at https://nevolin.be/codr/
Top comments (0)