Find the maximum sum after dividing array A into M Subarrays
Last Updated :
18 Apr, 2023
Given a sorted array A[] of size N and an integer M. You need to divide the array A[] into M non-empty consecutive subarray (1 ? M ? N) of any size such that each element is present in exactly one of the M-subarray. After dividing the array A[] into M subarrays you need to calculate the sum [max(i) - min(i)] where max(i) is the maximum element in the ith subarray and min(i) is the minimum element in the ith subarray (1 ? i ? M). After dividing array A into M subarrays, you need to compute the maximum sum.
Examples:
Input: A[] = {3, 6, 9, 10, 15}, M = 3
Output: 8
Explanation: The M subarrays are {3}, {6, 9}, {10, 15} and their maximum sum is 3-3 + 9-6 + 15-10 = 8
Input: A[] = {1, 2, 3, 4}, M = 4
Output: 0
Explanation: The M subarrays are {1}, {2}, {3}, {4} and their maximum sum is 1-1 + 2-2 + 3-3 + 4-4 = 0.
Approach: This can be solved with the following idea:
The idea is to check the co-efficient with which the array elements are included in the answer. If pair of adjacent elements Ai and Ai+1 belong to different subarrays then element Ai will be included in the answer with coefficient 1, and element Ai+1 with coefficient ?1. So they add value Ai?Ai+1 to the answer. If an element belongs to a subarray with length 1 then it will be included in the sum with coefficient 0 (because it will be included with coefficient 1 and ?1 simultaneously).
Elements at positions 1 and n will be included with coefficients ?1 and 1 respectively.
So initially our answer is An?A1. All we have to do is consider n?1 values A1?A2, A2?A3, …, An?1?An and add up the M?1 maximal ones to the answer
Below are the steps for the above approach:
- Declare a difference array diff of size N-1 which will store the difference between adjacent elements of array A[].
- Sort the difference array in increasing order.
- Initialize answer variable ans = A[N-1] - A[0] .
- Run a for loop from i = 0 to i < M-1 and update the answer variable ans = ans-diff[i].
- Return answer variable ans.
Below is the code for the above approach:
C++
// C++ Implementation of the above approach
#include <bits/stdc++.h>
using namespace std;
// Function performing calculation
int MsubarraySum(vector<int>& A, int M)
{
// Size of array A .
int N = A.size();
// Declaring difference array
vector<int> diff(N - 1);
// Storing difference between
// adjacent elements of A
for (int i = 0; i < N - 1; i++) {
diff[i] = A[i + 1] - A[i];
}
// Sorting difference array
// in increasing order.
sort(diff.begin(), diff.end());
// Initializing Answer variable
int ans = A[N - 1] - A[0];
// Running for loop and updating
// answer variable
for (int i = 0; i < M - 1; i++) {
ans -= (diff[i]);
}
// Returning answer value
return ans;
}
// Driver code
int main()
{
vector<int> A = { 3, 6, 9, 10, 15 };
int M = 3;
// Function call
cout << MsubarraySum(A, M);
return 0;
}
Java
import java.util.*;
public class Main {
// Function performing calculation
public static int MsubarraySum(ArrayList<Integer> A, int M) {
// Size of array A.
int N = A.size();
// Declaring difference array
ArrayList<Integer> diff = new ArrayList<Integer>(N - 1);
// Storing difference between
// adjacent elements of A
for (int i = 0; i < N - 1; i++) {
diff.add(A.get(i + 1) - A.get(i));
}
// Sorting difference array
// in increasing order.
Collections.sort(diff);
// Initializing Answer variable
int ans = A.get(N - 1) - A.get(0);
// Running for loop and updating
// answer variable
for (int i = 0; i < M - 1; i++) {
ans -= (diff.get(i));
}
// Returning answer value
return ans;
}
// Driver code
public static void main(String[] args) {
ArrayList<Integer> A = new ArrayList<Integer>(Arrays.asList(3, 6, 9, 10, 15));
int M = 3;
// Function call
System.out.println(MsubarraySum(A, M));
}
}
Python3
# Python Implementation of the above approach
# Function performing calculation
def MsubarraySum(A, M):
# Size of array A.
N = len(A)
# Declaring difference array
diff = [0] * (N - 1)
# Storing difference between
# adjacent elements of A
for i in range(N - 1):
diff[i] = A[i + 1] - A[i]
# Sorting difference array
# in increasing order.
diff.sort()
# Initializing Answer variable
ans = A[N - 1] - A[0]
# Running for loop and updating
# answer variable
for i in range(M - 1):
ans -= diff[i]
# Returning answer value
return ans
# Driver code
A = [3, 6, 9, 10, 15]
M = 3
# Function call
print(MsubarraySum(A, M))
# This code is contributed by prasad264
JavaScript
// Function performing calculation
function MsubarraySum(A, M) {
// Size of array A
let N = A.length;
// Declaring difference array
let diff = new Array(N - 1);
// Storing difference between adjacent elements of A
for (let i = 0; i < N - 1; i++) {
diff[i] = A[i + 1] - A[i];
}
// Sorting difference array in increasing order
diff.sort(function(a, b) {
return a - b;
});
// Initializing Answer variable
let ans = A[N - 1] - A[0];
// Running for loop and updating answer variable
for (let i = 0; i < M - 1; i++) {
ans -= diff[i];
}
// Returning answer value
return ans;
}
// Driver code
let A = [3, 6, 9, 10, 15];
let M = 3;
// Function call
console.log(MsubarraySum(A, M));
C#
using System;
using System.Collections.Generic;
using System.Linq;
class MainClass {
// Function performing calculation
public static int MsubarraySum(List<int> A, int M)
{
// Size of array A
int N = A.Count;
// Declaring difference array
List<int> diff = new List<int>(N - 1);
// Storing difference between
// adjacent elements of A
for (int i = 0; i < N - 1; i++) {
diff.Add(A[i + 1] - A[i]);
}
// Sorting difference array
// in increasing order.
diff.Sort();
// Initializing Answer variable
int ans = A[N - 1] - A[0];
// Running for loop and updating
// answer variable
for (int i = 0; i < M - 1; i++) {
ans -= diff[i];
}
// Returning answer value
return ans;
}
// Driver code
public static void Main()
{
List<int> A = new List<int>{ 3, 6, 9, 10, 15 };
int M = 3;
// Function call
Console.WriteLine(MsubarraySum(A, M));
}
}
Time Complexity: O(N)
Auxiliary Space: O(N)
Approach 2: Using Min Heap
In this approach, we create a min-heap from the difference array, and then remove the smallest M-1 differences one by one, subtracting them from the answer variable. The remaining difference after subtracting M-1 differences from the answer is the required maximum subarray sum.
C++
#include <bits/stdc++.h>
using namespace std;
int MsubarraySum(vector<int> A, int M)
{
// Size of array A.
int N = A.size();
// Declaring difference array
vector<int> diff(N - 1, 0);
// Storing difference between adjacent elements of A
for (int i = 0; i < N - 1; i++) {
diff[i] = A[i + 1] - A[i];
}
// Creating a min-heap from the difference array
make_heap(diff.begin(), diff.end(), greater<int>());
// Initializing Answer variable
int ans = A[N - 1] - A[0];
// Running for loop and updating answer variable
for (int i = 0; i < M - 1; i++) {
ans -= diff.front();
pop_heap(diff.begin(), diff.end(), greater<int>());
diff.pop_back();
}
// Returning answer value
return ans;
}
// Driver code
int main()
{
vector<int> A{ 3, 6, 9, 10, 15 };
int M = 3;
// Function call
cout << MsubarraySum(A, M);
return 0;
}
// This code is contributed by Susobhan Akhuli
Java
import java.util.*;
class Main {
public static int MsubarraySum(List<Integer> A, int M) {
int N = A.size();
List<Integer> diff = new ArrayList<Integer>(Collections.nCopies(N - 1, 0));
for (int i = 0; i < N - 1; i++) {
diff.set(i, A.get(i + 1) - A.get(i));
}
PriorityQueue<Integer> minHeap = new PriorityQueue<Integer>();
for (int d : diff) {
minHeap.offer(d);
}
int ans = A.get(N - 1) - A.get(0);
for (int i = 0; i < M - 1; i++) {
ans -= minHeap.poll();
}
return ans;
}
public static void main(String[] args) {
List<Integer> A = Arrays.asList(3, 6, 9, 10, 15);
int M = 3;
System.out.println(MsubarraySum(A, M));
}
}
Python3
import heapq
def MsubarraySum(A, M):
# Size of array A.
N = len(A)
# Declaring difference array
diff = [0] * (N - 1)
# Storing difference between
# adjacent elements of A
for i in range(N - 1):
diff[i] = A[i + 1] - A[i]
# Creating a min-heap from the difference array
heapq.heapify(diff)
# Initializing Answer variable
ans = A[N - 1] - A[0]
# Running for loop and updating
# answer variable
for i in range(M - 1):
ans -= heapq.heappop(diff)
# Returning answer value
return ans
# Driver code
A = [3, 6, 9, 10, 15]
M = 3
# Function call
print(MsubarraySum(A, M))
JavaScript
function MsubarraySum(A, M) {
// Size of array A.
let N = A.length;
// Declaring difference array
let diff = new Array(N - 1).fill(0);
// Storing difference between adjacent elements of A
for (let i = 0; i < N - 1; i++) {
diff[i] = A[i + 1] - A[i];
}
// Creating a min-heap from the difference array
diff.sort((a, b) => a - b);
// Initializing Answer variable
let ans = A[N - 1] - A[0];
// Running for loop and updating answer variable
for (let i = 0; i < M - 1; i++) {
ans -= diff[i];
}
// Returning answer value
return ans;
}
// Driver code
let A = [3, 6, 9, 10, 15];
let M = 3;
// Function call
console.log(MsubarraySum(A, M)); // Output: 8
C#
using System;
using System.Collections.Generic;
using System.Linq;
class GFG {
static int MsubarraySum(List<int> A, int M)
{
// Size of list A.
int N = A.Count;
// Declaring difference array
List<int> diff = new List<int>(N - 1);
// Storing difference between adjacent elements of A
for (int i = 0; i < N - 1; i++) {
diff.Add(A[i + 1] - A[i]);
}
// Creating a min-heap from the difference array
diff = new List<int>(
new SortedSet<int>(diff).ToList());
// Initializing Answer variable
int ans = A[N - 1] - A[0];
// Running for loop and updating answer variable
for (int i = 0; i < M - 1; i++) {
ans -= diff[0];
diff.RemoveAt(0);
}
// Returning answer value
return ans;
}
// Driver code
static void Main(string[] args)
{
List<int> A = new List<int>{ 3, 6, 9, 10, 15 };
int M = 3;
// Function call
Console.WriteLine(MsubarraySum(A, M));
}
}
// This code is contributed by Susobhan Akhuli
Time Complexity:
Creating a min-heap from the difference array takes O(N) time.
Removing the smallest M-1 differences from the heap takes O(M log N) time.
Updating the answer variable takes O(1) time.
Overall time complexity: O(N + M log N)
Auxiliary Space:
We use an extra space to store the difference array and create the min-heap, which takes O(N) space.
Similar Reads
Divide an array into k subarrays with minimum cost II
Given an array of integers arr[] of length n and two positive integers kk and len. The cost of an array is the value of its first element. For example, the cost of [2,3,4] is 2 and the cost of [4,1,2] is 4. You have to divide arr[] into k disjoint contiguous subarrays such that the difference betwee
11 min read
Maximum sum subarray after altering the array
Given an array arr[] of size N. The task is to find the maximum subarray sum possible after performing the given operation at most once. In a single operation, you can choose any index i and either the subarray arr[0...i] or the subarray arr[i...N-1] can be reversed. Examples: Input: arr[] = {3, 4,
15+ min read
Maximum sub-array sum after dividing array into sub-arrays based on the given queries
Given an array arr[] and an integer k, we can cut this array at k different positions where k[] stores the positions of all the cuts required. The task is to print maximum sum among all the cuts after every cut made. Every cut is of the form of an integer x where x denotes a cut between arr[x] and a
9 min read
Maximum sum after rearranging the array for K queries
Given two arrays arr[] containing N integers and Q[][] containing K queries where every query represents a range [L, R]. The task is to rearrange the array and find the maximum possible sum of all the subarrays where each subarray is defined by the elements of the array in the range [L, R] given by
10 min read
Find the maximum sum of Plus shape pattern in a 2-D array
Given a 2-D array of size N*M where, 3\leq N, M \leq 1000 . The task is to find the maximum value achievable by a + shaped pattern. The elements of the array can be negative.The plus(+) shape pattern is formed by taking any element with co-ordinate (x, y) as a center and then expanding it in all fou
10 min read
Subarray with largest sum after excluding its maximum element
Given an array arr[], the task is to find the starting and ending indices of the subarray with the largest sum after excluding its maximum element.Examples: Input: arr[] = {5, -2, 10, -1, 4} Output: 1 5 Explanation: Subarray[1:5] = {5, -2, 10, -1, 4} Sum of subarray excluding maximum element = 5 + (
9 min read
Maximum subarray sum in array formed by repeating the given array k times
Given an integer k and an integer array arr[] of n elements, the task is to find the largest sub-array sum in the modified array (formed by repeating the given array k times). For example, if arr[] = {1, 2} and k = 3 then the modified array will be {1, 2, 1, 2, 1, 2}. Examples: Input: arr[] = {1, 2}
12 min read
Maximize sum of means of two subsets formed by dividing given Array into them
Given an array arr[] of size N, the task is to find the maximum sum of means of 2 non-empty subsets of the given array such that each element is part of one of the subsets. Examples: Input: N = 2, arr[] = {1, 3}Output: 4.00Explanation: Since there are only two elements, make two subsets as {1} and {
5 min read
Maximum Subarray Sum after inverting at most two elements
Given an array arr[] of integer elements, the task is to find maximum possible sub-array sum after changing the signs of at most two elements.Examples: Input: arr[] = {-5, 3, 2, 7, -8, 3, 7, -9, 10, 12, -6} Output: 61 We can get 61 from index 0 to 10 by changing the sign of elements at 4th and 7th i
11 min read
Maximum subarray sum in an array created after repeated concatenation
Given an array and a number k, find the largest sum of contiguous array in the modified array which is formed by repeating the given array k times. Examples : Input : arr[] = {-1, 10, 20}, k = 2Output : 59After concatenating array twice, we get {-1, 10, 20, -1, 10, 20} which has maximum subarray sum
4 min read