Given a sorted array A[] of dimension N and an integer M. It’s essential divide the array A[] into M non-empty consecutive subarray (1 ≤ M ≤ N) of any dimension such that every factor is current in precisely one of many M-subarray. After dividing the array A[] into M subarrays it’s essential calculate the sum [max(i) – min(i)] the place max(i) is the utmost factor within the ith subarray and min(i) is the minimal factor within the ith subarray (1 ≤ i ≤ M). After dividing array A into M subarrays, it’s essential compute the utmost sum.
Examples:
Enter: A[] = {3, 6, 9, 10, 15}, M = 3
Output: 8
Clarification: The M subarrays are {3}, {6, 9}, {10, 15} and their most sum is 3-3 + 9-6 + 15-10 = 8Enter: A[] = {1, 2, 3, 4}, M = 4
Output: 0
Clarification: The M subarrays are {1}, {2}, {3}, {4} and their most sum is 1-1 + 2-2 + 3-3 + 4-4 = 0.
Strategy: This may be solved with the next thought:
The thought is to examine the co-efficient with which the array components are included within the reply. If pair of adjoining components Ai and Ai+1 belong to completely different subarrays then factor Ai might be included within the reply with coefficient 1, and factor Ai+1 with coefficient −1. So that they add worth Ai−Ai+1 to the reply. If a component belongs to a subarray with size 1 then will probably be included within the sum with coefficient 0 (as a result of will probably be included with coefficient 1 and −1 concurrently).
Components at positions 1 and n might be included with coefficients −1 and 1 respectively.
So initially our reply is An−A1. All we have now to do is think about n−1 values A1−A2, A2−A3, …, An−1−An and add up the M−1 maximal ones to the reply
Beneath are the steps for the above method:
- Declare a distinction array diff of dimension N-1 which can retailer the distinction between adjoining components of array A[].
- Type the distinction array in rising order.
- Initialize reply variable ans = A[N-1] – A[0] .
- Run a for loop from i = 0 to i < M-1 and replace the reply variable ans = ans-diff[i].
- Return reply variable ans.
Beneath is the code for the above method:
C++
// C++ Implementation of the above method
#embrace <bits/stdc++.h>
utilizing namespace std;
// Perform performing calculation
int MsubarraySum(vector<int>& A, int M)
{
// Measurement of array A .
int N = A.dimension();
// Declaring distinction array
vector<int> diff(N - 1);
// Storing distinction between
// adjoining components of A
for (int i = 0; i < N - 1; i++) {
diff[i] = A[i + 1] - A[i];
}
// Sorting distinction array
// in rising order.
kind(diff.start(), diff.finish());
// Initializing Reply variable
int ans = A[N - 1] - A[0];
// Working for loop and updating
// reply variable
for (int i = 0; i < M - 1; i++) {
ans -= (diff[i]);
}
// Returning reply worth
return ans;
}
// Driver code
int major()
{
vector<int> A = { 3, 6, 9, 10, 15 };
int M = 3;
// Perform name
cout << MsubarraySum(A, M);
return 0;
}
Time Complexity: O(N)
Auxiliary Area: O(N)