DSA
Largest Element
Covers: Sorting, Linear Scan. Optimal — Time O(n), Space O(1).
Given an array of integers nums, return the value of the largest element in the array
Sorting#
Sorting brings the largest element to the last index automatically, because a sorted ascending array has the maximum at the end. We can then return nums[n-1] in O(1). This approach is simple but overkill for the problem — sorting rearranges the entire array and costs O(n log n) when we only care about a single value.
- Sort the array
- Return the last element
Time Complexity: O(nlogn)
Space Complexity: O(1)
Linear Scan#
The intuition is to keep a running maximum as we walk through the array left to right. We initialize a variable largest to the smallest possible integer (INT_MIN) and update it whenever we find a bigger element. A single pass is sufficient because once we have seen every element, the running maximum is the global maximum. This beats sorting by reducing time complexity to O(n) while still using O(1) space.
- Scan the array, keeping note of largest element
class Solution {
public:
int largestElement(vector<int>& nums) {
int largest = INT_MIN;
for(int i=0;i<nums.size();i++){
if(nums[i]>largest)
largest = nums[i];
}
return largest;
}
};
Time Complexity: O(n)
Space Complexity: O(1)