Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[1793] Adding Solution ofmaximum-score-of-a-good-subarray.java #166

Merged
merged 5 commits into from
Oct 24, 2023
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
56 changes: 56 additions & 0 deletions Hard/maximum-score-of-a-good-subarray.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
class Solution {
public int maximumScore(int[] nums, int k) {
int [] nsr = findNSR(nums);
int [] nsl = findNSL(nums);

int score =0;
for(int i=0;i<nums.length;i++){
int l = nsl[i];
int r = nsr[i];
if(l+1 <= k && r-1>= k){
score = Math.max(score,nums[i] *(r-l-1));
}
}
return score;
}

//find next smaller element on right
public int[] findNSR(int [] arr){
int [] nsr = new int[arr.length];
Stack<Integer> s = new Stack<>();
for(int i=arr.length-1;i>=0;i--){
while(!s.isEmpty() && arr[i] <= arr[s.peek()] ){
s.pop();
}
if(s.isEmpty()){
nsr[i] =arr.length;
}
else{
nsr[i] = s.peek();
}
s.push(i);
}
return nsr;

}
//find next smaller element on left

public int[] findNSL(int [] arr){
int [] nsl = new int[arr.length];
Stack<Integer> s = new Stack<>();
for(int i=0;i<arr.length;i++){
while(!s.isEmpty() && arr[i] <= arr[s.peek()]){
s.pop();
}
if(s.isEmpty()){
nsl[i] =-1;
}
else{
nsl[i] = s.peek();
}
s.push(i);
}
return nsl;

}
}