Given an array arr[] consisting of N integers, the task is to find the minimum number of operations, which involves incrementing all elements of a subarray by 1, required to make the array non-increasing.
Examples:
Input:_ arr[] = {1, 3, 4, 1, 2} _
Output:_ 4 _
Explanation:
_In operation 1: Choose the subarray {1} and increase its value by 1. Now arr[] = {2, 3, 4, 1, 2} _
_In operation 2: Choose the subarray {2} and increase its value by 1. Now arr[] = {3, 3, 4, 1, 2} _
_In operation 3: Choose the subarray {3, 3} and increase its value by 1. Now arr[] = {4, 4, 4, 1, 2} _
_In operation 4: Choose the subarray {1} and increase its value by 1. Now arr[] = {4, 4, 4, 2, 2} _
Thus, it took 4 operations to make the array non-increasing.
Input:_ arr[] = {10, 9, 8, 7, 7} _
Output:_ 0 _
Explanation:
The array is already non-increasing
Recommended: Please try your approach on {IDE} first, before moving on to the solution.
Approach: The approach is based on the fact that the operations can only be performed on subarrays. So only check for contiguous elements. Below are the steps:
Below is the implementation of the above approach:
// Java program for the above approach
**import**
java.io.*;
**import**
java.util.*;
**class**
GFG {
// Function to find the minimum
// number of operations required to
// make the array non-increasing
**public**
**static**
**int**
getMinOps(``**int**``[] arr)
{
// Stores the count of
// required operations
**int**
res =
0``;
**for**
(``**int**
i =
0``;
i < arr.length -
1``; i++)
{
// If arr[i] > arr[i+1],
// no increments required.
// Otherwise, add their
// difference to the answer
res += Math.max(arr[i +
1``]
- arr[i],
0``);
}
// Return the result res
**return**
res;
}
// Driver Code
**public**
**static**
**void**
main(String[] args)
{
**int**``[] arr = {
1``,
3``,
4``,
1``,
2
};
System.out.println(getMinOps(arr));
}
}
Output:
4
Time Complexity:_ O(N) _
Auxiliary Space:_ O(1)_
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
#arrays #greedy #mathematical #subarray