DEV Community

Cover image for Road to Genius: advanced #35
Ilya Nevolin
Ilya Nevolin

Posted on

Road to Genius: advanced #35

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.

function maxProfit(prices) {
  let profit = 0;
  for (let i = 1; i < 🚀.length; i++) {
    if (prices[i] > prices[i - 1]) {
      profit = profit + ☃️[i] - prices[i - 💧];
    }
  }
  return profit;
}
let arr = [8, 2, 9, 1, 9];
let A = maxProfit(arr);

// 💧 = ? (number)
// 🚀 = ? (identifier)
// ☃️ = ? (identifier)
// such that A = 15 (number)
Enter fullscreen mode Exit fullscreen mode

We have seen a similar challenge like this many episodes ago, I remember the function maxProfit. Here we have to fix 3 bugs, let's go over them one by one.

for (let i = 1; i < 🚀.length; i++) {
Enter fullscreen mode Exit fullscreen mode

The first bug 🚀 on this line uses a property length, which is mostly used on arrays, and the only array we have here is prices.

The final two bugs appear on the same line:

if (prices[i] > prices[i - 1]) {
    profit = profit + ☃️[i] - prices[i - 💧];
}
Enter fullscreen mode Exit fullscreen mode

You can already make a calculated guess for ☃️, it's going to be prices because its neighbor and the if-condition reveals it.

The final bug 💧 should be a number, my initial guess is that 💧 should be 1, because it also appears in the if-condition like that. But let's make sure by analyzing the code.

This code is designed to calculate the max profit, it iterates over the prices and the if-condition decides whether a sale should be made or not, because it recomputes the profit (upon selling). In other words, when the new price (i) is greater than the previous price (i - 1) it will "sell".

The prices are: [8, 2, 9, 1, 9]
Here's some pseudo-code:

profit = 0
i = 1
N = 2 (= new price)
O = 8 (= old price)
N < O  --> do nothing

profit = 0
i = 2
N = 9
O = 2
N > O --> profit = profit + N-O = 0 + 9-2 = 7

profit = 7
i = 3
N = 1
O = 9
N < O --> do nothing

profit = 7
i = 4
N = 9
O = 1
N > O --> profit = profit + N-O = 7 + 9-1 = 15
Enter fullscreen mode Exit fullscreen mode

At the end profit is 15, which is exactly what the challenge expects:
such that A = 15 (number)

coding challenge answer

By solving these challenges you train yourself to be a better programmer. You'll learn newer and better ways of analyzing, debugging and improving code. As a result you'll be more productive and valuable in business. Join me on the Road to Genius and upgrade your programming skills, at https://nevolin.be/codr/

Top comments (0)