Maximize the sum of array by multiplying prefix of array with -1
Last Updated :
21 Aug, 2022
Given an array of elements 'arr', the task is to maximize the sum of the elements of this array after performing the following operation:
You can take any prefix of 'arr' and multiply each element of the prefix with '-1'.
In the first line, print the maximized sum than in the next line, print the index upto which the sequence of prefixes were chosen.
Examples:
Input: arr = {1, -2, -3, 4}
Output: 10
2 1 3 2
Flip the prefix till 2nd element then the sequence is -1 2 -3 4
Flip the prefix till 1st element then the sequence is 1 2 -3 4
Flip the prefix till 3rd element then the sequence is -1 -2 3 4
Flip the prefix till 2nd element then the sequence is 1 2 3 4
And, the final maximised sum is 10
Input: arr = {1, 2, 3, 4}
Output: 10
As, all the elements are already positive.
Approach: The max sum will always be \small \sum \left | A_i \right | as all the numbers of the array can be changed from negative to positive with the given operation.
- Traverse the array from left to right, if the element at index 'i' is negative then choose 'i' as the ending index of the prefix array and multiply each element by '-1'.
- Due to the operation in the previous step, all the elements in the array before index 'i' must be negative. So, take the prefix array ending at index 'i-1' and apply the same operation again to change all the elements to positive.
- Repeat the above steps until the complete array has been traversed and print the sum of all the elements along with all the ending indices of the chosen prefix arrays in the end.
Below is the implementation of the above approach:
C++
// C++ implementation of the approach
#include<bits/stdc++.h>
using namespace std;
void maxSum(int *a, int n)
{
vector<int> l;
// To store sum
int s = 0;
// To store ending indices
// of the chosen prefix array vect
for (int i = 0; i < n; i++)
{
// Adding the absolute
// value of a[i]
s += abs(a[i]);
if (a[i] >= 0)
continue;
// If i == 0 then there is no index
// to be flipped in (i-1) position
if (i == 0)
l.push_back(i + 1);
else
{
l.push_back(i + 1);
l.push_back(i);
}
}
// print the maximized sum
cout << s << endl;
// print the ending indices
// of the chosen prefix arrays
for (int i = 0; i < l.size(); i++)
cout << l[i] << " ";
}
// Driver Code
int main()
{
int n = 4;
int a[] = {1, -2, -3, 4};
maxSum(a, n);
}
// This code is contributed by
// Surendra_Gangwar
Java
// Java implementation of the approach
import java.util.*;
class GFG
{
static void maxSum(int []a, int n)
{
Vector<Integer> l = new Vector<Integer>();
// To store sum
int s = 0;
// To store ending indices
// of the chosen prefix array vect
for (int i = 0; i < n; i++)
{
// Adding the absolute
// value of a[i]
s += Math.abs(a[i]);
if (a[i] >= 0)
continue;
// If i == 0 then there is no index
// to be flipped in (i-1) position
if (i == 0)
l.add(i + 1);
else
{
l.add(i + 1);
l.add(i);
}
}
// print the maximised sum
System.out.println(s);
// print the ending indices
// of the chosen prefix arrays
for (int i = 0; i < l.size(); i++)
System.out.print(l.get(i) + " ");
}
// Driver Code
public static void main(String[] args)
{
int n = 4;
int a[] = {1, -2, -3, 4};
maxSum(a, n);
}
}
// This code is contributed by 29AjayKumar
Python3
# Python implementation of the approach
def maxSum(arr, n):
# To store sum
s = 0
# To store ending indices
# of the chosen prefix arrays
l = []
for i in range(len(a)):
# Adding the absolute
# value of a[i]
s += abs(a[i])
if (a[i] >= 0):
continue
# If i == 0 then there is
# no index to be flipped
# in (i-1) position
if (i == 0):
l.append(i + 1)
else:
l.append(i + 1)
l.append(i)
# print the
# maximised sum
print(s)
# print the ending indices
# of the chosen prefix arrays
print(*l)
n = 4
a = [1, -2, -3, 4]
maxSum(a, n)
C#
// C# implementation of the approach
using System;
using System.Collections.Generic;
class GFG
{
static void maxSum(int []a, int n)
{
List<int> l = new List<int>();
// To store sum
int s = 0;
// To store ending indices
// of the chosen prefix array vect
for (int i = 0; i < n; i++)
{
// Adding the absolute
// value of a[i]
s += Math.Abs(a[i]);
if (a[i] >= 0)
continue;
// If i == 0 then there is no index
// to be flipped in (i-1) position
if (i == 0)
l.Add(i + 1);
else
{
l.Add(i + 1);
l.Add(i);
}
}
// print the maximised sum
Console.WriteLine(s);
// print the ending indices
// of the chosen prefix arrays
for (int i = 0; i < l.Count; i++)
Console.Write(l[i] + " ");
}
// Driver Code
public static void Main(String[] args)
{
int n = 4;
int []a = {1, -2, -3, 4};
maxSum(a, n);
}
}
// This code is contributed by PrinciRaj1992
PHP
<?php
// PHP implementation of the approach
function maxSum($a, $n)
{
// To store sum
$s = 0;
// To store ending indices
// of the chosen prefix arrays
$l = array();
for ($i = 0; $i < count($a); $i++)
{
// Adding the absolute
// value of a[i]
$s += abs($a[$i]);
if ($a[$i] >= 0)
continue;
// If i == 0 then there is
// no index to be flipped
// in (i-1) position
if ($i == 0)
array_push($l, $i + 1);
else
{
array_push($l, $i + 1);
array_push($l, $i);
}
}
// print the
// maximised sum
echo $s . "\n";
// print the ending indices
// of the chosen prefix arrays
for($i = 0; $i < count($l); $i++)
echo $l[$i] . " ";
}
// Driver Code
$n = 4;
$a = array(1, -2, -3, 4);
maxSum($a, $n);
// This code is contributed by mits
?>
JavaScript
<script>
// Javascript implementation of the above approach
function maxSum(a, n)
{
let l = [];
// To store sum
let s = 0;
// To store ending indices
// of the chosen prefix array vect
for (let i = 0; i < n; i++)
{
// Adding the absolute
// value of a[i]
s += Math.abs(a[i]);
if (a[i] >= 0)
continue;
// If i == 0 then there is no index
// to be flipped in (i-1) position
if (i == 0)
l.push(i + 1);
else
{
l.push(i + 1);
l.push(i);
}
}
// print the maximised sum
document.write(s + "<br/>");
// print the ending indices
// of the chosen prefix arrays
for (let i = 0; i < l.length; i++)
document.write(l[i] + " ");
}
// driver code
let n = 4;
let a = [1, -2, -3, 4];
maxSum(a, n);
</script>
Time Complexity: O(n)
Auxiliary Space: O(n)
Similar Reads
Maximize the sum of array after multiplying a prefix and suffix by -1 Given an array arr[] of length N, the task is to maximize the sum of all the elements of the array by performing the following operations at most once. Choose a prefix of the array and multiply all the elements by -1.Choose a suffix of the array and multiply all the elements by -1. Examples: Input:
7 min read
Maximize the sum of array after multiplying a prefix and suffix by -1 Given an array arr[] of length N, the task is to maximize the sum of all the elements of the array by performing the following operations at most once. Choose a prefix of the array and multiply all the elements by -1.Choose a suffix of the array and multiply all the elements by -1. Examples: Input:
7 min read
Rearrange array elements to maximize the sum of MEX of all prefix arrays Given an array arr[] of size N, the task is to rearrange the array elements such that the sum of MEX of all prefix arrays is the maximum possible. Note: MEX of a sequence is the minimum non-negative number not present in the sequence. Examples: Input: arr[] = {2, 0, 1}Output: 0, 1, 2Explanation:Sum
7 min read
Maximum array sum with prefix and suffix multiplications with -1 allowed Given N elements (both positive and negative). Find the maximum sum, provided that the first operation is to take some prefix of the sequence and multiply all numbers in this prefix by -1. The second operation is to take some suffix and multiply all numbers in it by -1. The chosen prefix and suffix
8 min read
Maximize product of a matrix by repeatedly multiplying pairs of adjacent cells with -1 Given a matrix mat[][] of dimensions NxN consisting of integers, the task is to find the maximum product of elements of the matrix mat[][] possible repeatedly multiplying pairs of adjacent cells by -1. Note: The value of any matrix element can be changed by -1 at most once. Examples: Input: arr[][]
8 min read
Maximize number of indices with prefix sum equal to 0 Given an array arr[] of size N, you can perform the following operation on the array any number of times: If arr[i]=0, we can replace it with any integer. Your task is to maximize the number of indices having prefix sum = 0. Examples: Input: N = 7, arr[] = {1, -1, 0, 2, 4, 2, 0, 1}Output: 3Explanati
10 min read