Skip to content

Commit

Permalink
solution(java): 1793. Maximum Score of a Good Subarray
Browse files Browse the repository at this point in the history
1793. Maximum Score of a Good Subarray
- Java
  • Loading branch information
godkingjay authored Oct 24, 2023
2 parents 8551fdf + 198716d commit 336a315
Show file tree
Hide file tree
Showing 2 changed files with 79 additions and 0 deletions.
24 changes: 24 additions & 0 deletions Hard/1793. Maximum Score of a Good Subarray/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
This Is Hard Problem of LeetCode
Problem Number 1793
LinK:https://leetcode.com/problems/maximum-score-of-a-good-subarray/
Maximum Score of a Good Subarray
This Java code helps you find the maximum possible score of a good subarray in an array of integers. A good subarray is defined as one where i <= k <= j, and the score of a subarray is calculated as min(nums[i], nums[i+1], ..., nums[j]) * (j - i + 1). The code uses a specific algorithm to find the optimal subarray that maximizes this score.

Usage
To use this code, follow these steps:

Copy the code and paste it into your Java project.

Implement the maxGoodSubarrayScore method, passing in the array of integers (nums) and the integer k as parameters.

The method will return the maximum possible score for a good subarray according to the defined algorithm.

Method Description
maxGoodSubarrayScore(int[] nums, int k)
This method calculates the maximum possible score for a good subarray in the given array nums using a specific algorithm.

Parameters:

nums: An array of integers.
k: The integer representing the pivot point.
Returns: The maximum possible score of a good subarray.
55 changes: 55 additions & 0 deletions Hard/1793. Maximum Score of a Good Subarray/Solution.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@

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;
}
}

0 comments on commit 336a315

Please sign in to comment.