Hi! Long time no see.
I've been so busy looking for a job, working, studying English, and learning new tech stacks... T_T
But algorithms are one of the most important things when preparing for a job, so I'm back! Hahaha.
Anyway, today I solved a problem about arrays.
First, this is my own code. It was too long and unfortunately, it caused a time limit exceeded (TLE) error... 😭
Why did I write my code like this?
Because I needed to find the largest average.
So, first, I created an array and stored the subarrays.
Then, in the second for loop, I calculated the sum and stored it in another array.
Finally, in the third for loop, I computed the averages and returned the maximum value using the Math.max() method.
Here’s the simple code from GPT.
He? She? (Not sure 🤔) said that some parts of my code were duplicated, and I created a new array using the slice method, which increased the time complexity.
Also, I made three arrays, which affected memory usage...
My code was horrible... 😭
So, GPT suggested using the sliding window approach?
It was my first time learning about sliding window...
So the key part is:
For example, let's take [10, 12, -5, -6, 50, 3] with k = 4.
- First sum:
10 + 12 - 5 - 6 = 11 This is the sum of the first k elements. - Second sum (Sliding the window):
11 - nums[0] + nums[4] = 11 - 10 + 50 = 51
Did you get it?
Each time, the window moves to the next element while keeping the size fixed.
Why do we subtract nums[0]?
Because there's a fixed range limitation (k elements).
So, we subtract the first element from the previous window and then add the next element to get the new sum.
'열정가득한 개발자의 이야기 > Javascript Algorithm' 카테고리의 다른 글
1071. Greatest Common Divisor of Strings (JS) (0) | 2025.03.22 |
---|---|
151. Reverse Words in a String (Javascript) (0) | 2025.03.20 |
leetcode 575. Distribute Candies (javascript) (1) | 2025.01.27 |
500. Keyboard Row (javascript) (0) | 2025.01.26 |
leet code 409. Longest Palindrome (0) | 2025.01.18 |