
Mall Time
Malls became a popular place to go to in the US during the 20th century. The place gets busy during the day, weekends, and holidays. It is a great place to hang with friend because the mall has many stores to go to from candy stores to food courts to game shops.
Now this is a new week, it is time for another algorithm. The question is regarding malls. The question is given a time of day, when is the most busy time of the year. An example data point is
[ 1440084737, 4, 0 ].
The first number is the time that has elapsed since January 1, 1970; second number is the number of people; third number is either 1 or 0 that means enter or exit respectively.
First thing we want to do is set up a few variables
var count = 0
var max = 0
var maxTime = 0.
Then we use a for-loop to iterate through each data point and either add or subtract from the count
for(var x = 0; x < data.length; x++){
if (data[x][2] == 1){
count += data[x][1]
}
else if (data[x][2] == 0){
count -= data[x][1]
}.
Sometimes the time stamps are the same and if they are, we simply continue.
if (x < data.length - 1 && data[x][0] == data[x+1][0]){
continue
}
Next, if the count is greater than the max, set the max to equal the count and the maxTime to equal to data[x][0].
if (count > max){ max = count
maxTime = data[x][0]
}
Full code is
function findBusiestPeriod(data) {
// your code goes here
var count = 0
var max = 0
var maxTime = 0
for(var x = 0; x < data.length; x++){
if (data[x][2] == 1){
count += data[x][1]
}
else if (data[x][2] == 0){
count -= data[x][1]
} if (x < data.length - 1 && data[x][0] == data[x+1][0]){
continue
}
if (count > max){ max = count
maxTime = data[x][0]
}
return maxTime }
}
Let’s give it a try. Given the data
data =
[ [1487799425, 14, 1],
[1487799425, 4, 0],
[1487799425, 2, 0],
[1487800378, 10, 1],
[1487801478, 18, 0],
[1487801478, 18, 1],
[1487901013, 1, 0],
[1487901211, 7, 1],
[1487901211, 7, 0] ]
find the max time. The max time is 1487800378 and we see that it is indeed the case.

If there is a better way to solve it, let me know.