Day - 69
Assalamu alaykum, everyone! How are you dears?
We have about 31 days to complete the challenge. I am glad to share solutions everyday! This challenge helps not only to gain new knowledge, but also to make new acquaintances! I want this benefit not only for myself but also for you. You can also create your own challenges and achieve even higher goals.
So, let's start coding!
Time Complexity:
The time complexity of this code is O(n log n), where n is the number of stones. This is because the while loop runs at most n times, and each time it runs, the Math.max function is called, which has a time complexity of O(log n)
Space Complexity:
The space complexity of this code is O(n), because the stones array is always stored in memory.
Code:
/*
?* @param {number[]} stones
?* @return {number}
?*/
var lastStoneWeight = function (stones) {
? while (stones.length > 1) {
? ? let max1 = Math.max(...stones);
? ? stones.splice(stones.indexOf(max1), 1);
? ? let max2 = Math.max(...stones);
? ? stones.splice(stones.indexOf(max2), 1);
? ? if (max1 !== max2) stones.push(Math.abs(max1 - max2));
? }
? return stones[0] || 0;
};
That's all about today's challenge! It is time to share the post with your friends!
Thanks for your attention!