Grokking Data Structures & Algorithms for Coding Interviews
Ask Author
Back to course home

0% completed

Vote For New Content
Array problem #4: a better solution?

tranlannhi

Oct 23, 2023

Would the solution with time O(logn) be better than O(n)? Could you please provide input for the following solution?

class Solution { largestAltitude(gain) { let maxAltitude = 0; let altChange = new Array(gain.length) altChange[0] = gain[0] for (let i=1; i< gain.length; i++){ altChange[i] = gain[i] + altChange[i-1] } altChange.sort((a,b) => b-a) maxAltitude = altChange[0] return maxAltitude; } }

0

0

Comments
Comments
K
Kelvin Cuesta2 years ago

This would still be O(n) instead of O(logn). You are iterating through the gain array linearly and then sorting after the fact.

Naman Jindal
Naman Jindala year ago

Your solution is O(nlogn) as you are sorting the array. O(n) solution will be better.

On this page

Problem Statement

Examples

Solution

Algorithm Walkthrough

Code

Complexity Analysis

Time Complexity

Space Complexity