Day 44 of LeetCode Challenge

Cloud and DevOps Engineer with hands-on expertise in AWS, CI/CD pipelines, Docker, Kubernetes, and Monitoring tools. Adept at building and automating scalable, fault-tolerant cloud infrastructures, and consistently improving system performance, security, and reliability in dynamic environments.
Problem 1: Kth Largest Element in an Array
Link to the problem: https://leetcode.com/problems/kth-largest-element-in-an-array/

class Solution {
public int findKthLargest(int[] nums, int k) {
PriorityQueue<Integer> pq = new PriorityQueue<>();
for(int i:nums) pq.offer(i);
while(pq.size()>k) pq.poll();
return ((Integer) pq.peek()).intValue();
}
}
Problem 2: Longest Mountain in Array
Link to the problem: https://leetcode.com/problems/longest-mountain-in-array/

class Solution {
public int longestMountain(int[] arr) {
int n = arr.length;
if(n<3) return 0;
int i=1;
int res = 0;
while(i<n-1){
boolean isPeak = ((arr[i]>arr[i-1]) && arr[i]>arr[i+1]);
if(isPeak){
int left = i;
int right = i;
while(left>0 && arr[left]>arr[left-1]) left--;
while(right<n-1 && arr[right]>arr[right+1]) right++;
int currLen = right-left+1;
res = Math.max(res, currLen);
i=right;
}else{
i++;
}
}
return res;
}
}
Problem 3: Majority Element
Link to the problem: https://leetcode.com/problems/majority-element/

class Solution {
public int majorityElement(int[] nums) {
int count = 0;
int candidate = -1;
for(int i:nums){
if(count==0){
count++;
candidate = i;
}else if(candidate==i) count++;
else{
count--;
if(count==0){
count++;
candidate = i;
}
}
}
count = 0;
for(int i:nums) if(candidate==i) count++;
return count>nums.length/2?candidate:-1;
}
}
Problem 4: Sliding Window Maximum
Link to the problem: https://leetcode.com/problems/sliding-window-maximum/

class Solution {
public int[] maxSlidingWindow(int[] nums, int k) {
int n = nums.length;
if(k>=n){
int num = Integer.MIN_VALUE;
for(int i:nums) num = Math.max(num, i);
int[] res = new int[1];
res[0] = num;
return res;
}
ArrayList<Integer> list = new ArrayList<>();
Deque<Integer> dq = new ArrayDeque<>();
for(int i=0; i<k; i++){
while(!dq.isEmpty() && nums[dq.peekLast()]<=nums[i]) dq.pollLast();
dq.addLast(i);
}
for(int i=k; i<n; i++){
list.add(nums[dq.peekFirst()]);
while(!dq.isEmpty() && dq.peekFirst()<i-k+1) dq.pollFirst();
while(!dq.isEmpty() && nums[dq.peekLast()]<=nums[i]) dq.pollLast();
dq.addLast(i);
}
list.add(nums[dq.peekFirst()]);
int[] res = new int[list.size()];
for(int i=0; i<list.size(); i++) res[i] = ((Integer) list.get(i)).intValue();
return res;
}
}
Problem 5: Last Moment before all Ants Fall Of a Plank
Link to the problem: https://leetcode.com/problems/last-moment-before-all-ants-fall-out-of-a-plank/

class Solution {
public int getLastMoment(int n, int[] left, int[] right) {
int res = 0;
for(int i:left) res = Math.max(res, i);
for(int i:right) res = Math.max(res, n-i);
return res;
}
}



