Maximum Score of a Good Subarray in Java

The task is to determine the maximum score of a "good" subarray given an integer k and an array num of integers. A subarray's length (j - i + 1) multiplied by the minimum value within it determines its score. A subarray's start and end indices (i, j) define it. If the index k is present in the subarray, it is considered "good"; so, i <= k <= j. The problem is to find the highest possible score that any "good" subarray may obtain. We must quickly identify subarrays that include k and have high scores, which are determined by multiplying the subarray's smallest element by its length, to solve this task.

A subarray (i, j) has a score that may be expressed as min(nums[i], nums[i+1],..., nums[j]) * (j - i + 1). When i <= k <= j, a subarray is considered excellent.

Return a good subarray the highest score that may be obtained.

Example 1:

Input:

int n = [1, 4, 3, 7, 4, 5]

int k = 3

Output:

 
The Maximum Score of a Good Subarray is 15   

Explanation:

The ideal subarray is (1, 5) with a score of min(4,3,7,4,5) * (5-1+1) = 3 * 5 = 15.

Example 2:

Input:

int n = [5, 5, 4, 5, 4, 1, 1, 1]

int k = 0

Output:

 
The Maximum Score of a Good Subarray is 20   

Explanation: The ideal subarray is (0, 4) with a score of min(5, 5, 4, 5, 4) * (4 - 0 + 1) = 4 * 5 = 20.

Two Pointer Approach

Algorithm:

Step 1: Set the value at index k for the minimum variable mini and the result variable res. K should be used as the subarray's midpoint to begin with.

Step 2: Set the initial values of two pointers, I and j, to k. The subarray will be expanded with the aid of these hints.

Step 3: As long as one of the pointers (I or j) is not near the array's edge.

Step 3.1: Increase j if I am at the left border (0).

Step 3.2: Decrease I if j is at the appropriate border (n - 1).

Step 3.3: To extend the subarray to the right, increase j if the element at Array[I - 1] is smaller than the element at Array[j + 1].

Step 3.4: If not, decrease I to make the subarray larger to the left.

Step 4: Add the minimum value between A[i] and A[j] to mini.

Step 5: Update res to include mini * (j - I + 1) and the maximum of the existing res. This is a critical step since it determines the current subarray's score and records the highest score that was discovered.

Step 6: Carry on until one of the arrows crosses a boundary.

Step 7: As the last step, return res as the highest possible score for a quality subarray.

Implementation:

FileName: MaxiScore.java

Output:

 
The Maximum Score of a Good Subarray is: 15