Maximum value obtained by performing given operations in an Array
Last Updated :
04 Oct, 2023
Given an array arr[], the task is to find out the maximum obtainable value. The user is allowed to add or multiply the two consecutive elements. However, there has to be at least one addition operation between two multiplication operations (i.e), two consecutive multiplication operations are not allowed.
Let the array elements be 1, 2, 3, 4 then 1 * 2 + 3 + 4 is a valid operation whereas 1 + 2 * 3 * 4 is not a a valid operation as there are consecutive multiplication operations.
Examples:
Input : 5 -1 -5 -3 2 9 -4
Output : 33
Explanation:
The maximum value obtained by following the above conditions is 33.
The sequence of operations are given as:
5 + (-1) + (-5) * (-3) + 2 * 9 + (-4) = 33Input : 5 -3 -5 2 3 9 4
Output : 62
Approach:
This problem can be solved by using dynamic programming.
- Assuming 2D array dp[][] of dimensions n * 2.
- dp[i][0] represents the maximum value of the array up to ith position if the last operation is addition.
- dp[i][1] represents the maximum value of the array up to ith position if the last operation is multiplication.
Now, since consecutive multiplication operation is not allowed, the recurrence relation can be considered as :
dp[i][0] = max(dp[ i - 1][0], dp[ i - 1][1]) + a[ i + 1];
dp[i][1] = dp[i - 1][0] - a[i] + a[i] * a[i + 1];
The base cases are:
dp[0][0] = a[0] + a[1];
dp[0][1] = a[0] * a[1];
Below is the implementation of the above approach:
C++
// C++ implementation of the above approach
#include <bits/stdc++.h>
using namespace std;
// A function to calculate the maximum value
void findMax(int a[], int n)
{
int dp[n][2];
memset(dp, 0, sizeof(dp));
// basecases
dp[0][0] = a[0] + a[1];
dp[0][1] = a[0] * a[1];
//Loop to iterate and add the max value in the dp array
for (int i = 1; i <= n - 2; i++) {
dp[i][0] = max(dp[i - 1][0], dp[i - 1][1]) + a[i + 1];
dp[i][1] = dp[i - 1][0] - a[i] + a[i] * a[i + 1];
}
cout << max(dp[n - 2][0], dp[n - 2][1]);
}
// Driver Code
int main()
{
int arr[] = { 5, -1, -5, -3, 2, 9, -4 };
findMax(arr, 7);
}
Java
// Java implementation of the above approach
import java.util.*;
class GFG
{
// A function to calculate the maximum value
static void findMax(int []a, int n)
{
int dp[][] = new int[n][2];
int i, j;
for (i = 0; i < n ; i++)
for(j = 0; j < 2; j++)
dp[i][j] = 0;
// basecases
dp[0][0] = a[0] + a[1];
dp[0][1] = a[0] * a[1];
// Loop to iterate and add the
// max value in the dp array
for (i = 1; i <= n - 2; i++)
{
dp[i][0] = Math.max(dp[i - 1][0],
dp[i - 1][1]) + a[i + 1];
dp[i][1] = dp[i - 1][0] - a[i] +
a[i] * a[i + 1];
}
System.out.println(Math.max(dp[n - 2][0],
dp[n - 2][1]));
}
// Driver Code
public static void main (String[] args)
{
int arr[] = { 5, -1, -5, -3, 2, 9, -4 };
findMax(arr, 7);
}
}
// This code is contributed by AnkitRai01
Python3
# Python3 implementation of the above approach
import numpy as np
# A function to calculate the maximum value
def findMax(a, n) :
dp = np.zeros((n, 2));
# basecases
dp[0][0] = a[0] + a[1];
dp[0][1] = a[0] * a[1];
# Loop to iterate and add the max value in the dp array
for i in range(1, n - 1) :
dp[i][0] = max(dp[i - 1][0], dp[i - 1][1]) + a[i + 1];
dp[i][1] = dp[i - 1][0] - a[i] + a[i] * a[i + 1];
print(max(dp[n - 2][0], dp[n - 2][1]), end ="");
# Driver Code
if __name__ == "__main__" :
arr = [ 5, -1, -5, -3, 2, 9, -4 ];
findMax(arr, 7);
# This code is contributed by AnkitRai01
C#
// C# implementation of the above approach
using System;
class GFG
{
// A function to calculate the maximum value
static void findMax(int []a, int n)
{
int [,]dp = new int[n, 2];
int i, j;
for (i = 0; i < n ; i++)
for(j = 0; j < 2; j++)
dp[i, j] = 0;
// basecases
dp[0, 0] = a[0] + a[1];
dp[0, 1] = a[0] * a[1];
// Loop to iterate and add the
// max value in the dp array
for (i = 1; i <= n - 2; i++)
{
dp[i, 0] = Math.Max(dp[i - 1, 0], dp[i - 1, 1]) + a[i + 1];
dp[i, 1] = dp[i - 1, 0] - a[i] + a[i] * a[i + 1];
}
Console.WriteLine(Math.Max(dp[n - 2, 0], dp[n - 2, 1]));
}
// Driver Code
public static void Main()
{
int []arr = { 5, -1, -5, -3, 2, 9, -4 };
findMax(arr, 7);
}
}
// This code is contributed by AnkitRai01
JavaScript
<script>
// javascript implementation of the above approach
// A function to calculate the maximum value
function findMax(a , n) {
var dp = Array(n).fill().map(()=>Array(2).fill(0));
var i, j;
for (i = 0; i < n; i++)
for (j = 0; j < 2; j++)
dp[i][j] = 0;
// basecases
dp[0][0] = a[0] + a[1];
dp[0][1] = a[0] * a[1];
// Loop to iterate and add the
// max value in the dp array
for (i = 1; i <= n - 2; i++) {
dp[i][0] = Math.max(dp[i - 1][0], dp[i - 1][1]) + a[i + 1];
dp[i][1] = dp[i - 1][0] - a[i] + a[i] * a[i + 1];
}
document.write(Math.max(dp[n - 2][0], dp[n - 2][1]));
}
// Driver Code
var arr = [ 5, -1, -5, -3, 2, 9, -4 ];
findMax(arr, 7);
// This code contributed by Rajput-Ji
</script>
Time complexity: O(n) where n is size of given array
Auxiliary space: O(n) because it is using extra space for array "dp"
Efficient approach : Space optimization O(1)
In previous approach the current value ( dp[i] ) is depend upon the ( dp[i-1] ) so which is just the previous computation of DP array. So to optimize the space complexity we only require the computation of previous index.
Implementation Steps:
- Create variables prev_sum and prev_prod to get the computation of just previous index of DP.
- Initialize them with a[0] + a[1] and a[0] * a[1] resp.
- Now create variables curr_sum and curr_prod to get the current value from previous computation.
- Create variable max_val to store the final result.
- Now iterate over subproblems and get the current value from prev_sum and prev_prod.
- After every iteration assign values of curr_sum to prev_sum and curr_prod to prev_prod to iterate further.
- At last print answer stored in max_val.
Implementation:
C++
// C++ program for above approach
#include <bits/stdc++.h>
using namespace std;
// A function to calculate the maximum value
void findMax(int a[], int n)
{
// initialize variables for previous sum and product
int prev_sum = a[0] + a[1];
int prev_prod = a[0] * a[1];
// initialize variables for current sum and product
int curr_sum, curr_prod;
// to store the final result
int max_val;
// Loop to iterate and update the max value
for (int i = 1; i <= n - 2; i++) {
// get current value from previous computation
// store in previous sum and previous product
curr_sum = max(prev_sum, prev_prod) + a[i + 1];
curr_prod = prev_sum - a[i] + a[i] * a[i + 1];
// update answer
max_val = max(curr_sum, curr_prod);
// assigning values of currsum and currproduct
// to prev sum and product to iterate further
prev_sum = curr_sum;
prev_prod = curr_prod;
}
// print the final result
cout << max_val;
}
// Driver Code
int main()
{
int arr[] = { 5, -1, -5, -3, 2, 9, -4 };
// function call
findMax(arr, 7);
}
Java
import java.util.*;
class Main {
// A function to calculate the maximum value
static void findMax(int a[], int n)
{
// initialize variables for previous sum and product
int prev_sum = a[0] + a[1];
int prev_prod = a[0] * a[1];
// initialize variables for current sum and product
int curr_sum, curr_prod;
// to store the final result
int max_val = 0;
// Loop to iterate and update the max value
for (int i = 1; i <= n - 2; i++) {
// get current value from previous computation
// store in previous sum and previous product
curr_sum
= Math.max(prev_sum, prev_prod) + a[i + 1];
curr_prod = prev_sum - a[i] + a[i] * a[i + 1];
// update answer
max_val = Math.max(curr_sum, curr_prod);
// assigning values of currsum and currproduct
// to prev sum and product to iterate further
prev_sum = curr_sum;
prev_prod = curr_prod;
}
// print the final result
System.out.println(max_val);
}
// Driver Code
public static void main(String[] args)
{
int arr[] = { 5, -1, -5, -3, 2, 9, -4 };
// function call
findMax(arr, 7);
}
}
Python3
# Python program for above approach
# A function to calculate the maximum value
def findMax(a, n):
# initialize variables for previous sum and product
prev_sum = a[0] + a[1]
prev_prod = a[0] * a[1]
# initialize variables for current sum and product
curr_sum, curr_prod = 0, 0
# to store the final result
max_val = 0
# Loop to iterate and update the max value
for i in range(1, n - 1):
# get current value from previous computation
# store in previous sum and previous product
curr_sum = max(prev_sum, prev_prod) + a[i + 1]
curr_prod = prev_sum - a[i] + a[i] * a[i + 1]
# update answer
max_val = max(curr_sum, curr_prod)
# assigning values of currsum and currproduct
# to prev sum and product to iterate further
prev_sum = curr_sum
prev_prod = curr_prod
# print the final result
print(max_val)
# Driver Code
arr = [5, -1, -5, -3, 2, 9, -4]
# function call
findMax(arr, 7)
C#
using System;
public class Program
{
public static void Main()
{
int[] arr = { 5, -1, -5, -3, 2, 9, -4 };
findMax(arr, 7);
}
// A function to calculate the maximum value
static void findMax(int[] a, int n)
{
// initialize variables for previous sum and product
int prev_sum = a[0] + a[1];
int prev_prod = a[0] * a[1];
// initialize variables for current sum and product
int curr_sum, curr_prod;
// to store the final result
int max_val = 0;
// Loop to iterate and update the max value
for (int i = 1; i <= n - 2; i++)
{
// get current value from previous computation
// store in previous sum and previous product
curr_sum = Math.Max(prev_sum, prev_prod) + a[i + 1];
curr_prod = prev_sum - a[i] + a[i] * a[i + 1];
// update answer
max_val = Math.Max(curr_sum, curr_prod);
// assigning values of currsum and currproduct
// to prev sum and product to iterate further
prev_sum = curr_sum;
prev_prod = curr_prod;
}
// print the final result
Console.WriteLine(max_val);
}
}
JavaScript
function findMax(arr) {
// Initialize variables for previous sum and product
let prev_sum = arr[0] + arr[1];
let prev_prod = arr[0] * arr[1];
// Initialize variables for current sum and product
let curr_sum, curr_prod;
// Initialize a variable to store the final result
let max_val;
// Loop to iterate and update the max value
for (let i = 1; i < arr.length - 1; i++) {
// Get the current value from previous computation
// Store it in current sum and current product
curr_sum = Math.max(prev_sum, prev_prod) + arr[i + 1];
curr_prod = prev_sum - arr[i] + arr[i] * arr[i + 1];
// Update the answer
max_val = Math.max(curr_sum, curr_prod);
// Assign values of curr_sum and curr_prod
// to prev_sum and prev_prod to iterate further
prev_sum = curr_sum;
prev_prod = curr_prod;
}
// Print the final result
console.log(max_val);
}
// Driver Code
const arr = [5, -1, -5, -3, 2, 9, -4];
// Function call
findMax(arr);
Output
33
Time complexity: O(n) where n is size of given array
Auxiliary space: O(1) because no extra space is used.
Similar Reads
Maximum score possible after performing given operations on an Array
Given an array A of size N, the task is to find the maximum score possible of this array. The score of an array is calculated by performing the following operations on the array N times: If the operation is odd-numbered, the score is incremented by the sum of all elements of the current array. If th
15+ min read
Find the Maximum sum of the Array by performing the given operations
Given an Array A[] of size N with repeated elements and all array elements are positive, the task is to find the maximum sum by applying the given operations: Select any 2 indexes and select 2 integers(say x and y) such that the product of the elements(x and y) is equal to the product of the element
5 min read
Maximum Possible Product in Array after performing given Operations
Given an array with size N. You are allowed to perform two types of operations on the given array as described below: Choose some position i and j, such that (i is not equals to j), replace the value of a[j] with a[i]*a[j] and remove the number from the ith cell.Choose some position i and remove the
13 min read
Maximum possible Array sum after performing given operations
Given array arr[] of positive integers, an integer Q, and arrays X[] and Y[] of size Q. For each element in arrays X[] and Y[], we can perform the below operations: For each query from array X[] and Y[], select at most X[i] elements from array arr[] and replace all the selected elements with integer
9 min read
Maximize the minimum value of Array by performing given operations at most K times
Given array A[] of size N and integer K, the task for this problem is to maximize the minimum value of the array by performing given operations at most K times. In one operation choose any index and increase that array element by 1. Examples: Input: A[] = {3, 1, 2, 4, 6, 2, 5}, K = 8Output: 4Explana
10 min read
Maximise minimum element possible in Array after performing given operations
Given an array arr[] of size N. The task is to maximize the minimum value of the array after performing given operations. In an operation, value x can be chosen and A value 3 * x can be subtracted from the arr[i] element.A value x is added to arr[i-1]. andA value of 2 * x can be added to arr[i-2]. F
11 min read
Maximum possible array sum after performing the given operation
Given an array arr[] of size N, the task is to find the maximum sum of the elements of the array after applying the given operation any number of times. In a single operation, choose an index 1 ? i < N and multiply both arr[i] and arr[i - 1] by -1.Examples: Input: arr[] = {-10, 5, -4} Output: 19
9 min read
Maximum sum of all elements of array after performing given operations
Given an array of integers. The task is to find the maximum sum of all the elements of the array after performing the given two operations once each. The operations are: 1. Select some(possibly none) continuous elements from the beginning of the array and multiply by -1. 2. Select some(possibly none
7 min read
Maximize sum of array elements removed by performing the given operations
Given two arrays arr[] and min[] consisting of N integers and an integer K. For each index i, arr[i] can be reduced to at most min[i]. Consider a variable, say S(initially 0). The task is to find the maximum value of S that can be obtained by performing the following operations: Choose an index i an
8 min read
Maximum value in an array after m range increment operations
Consider an array of size n with all initial values as 0. We need to perform the following m range increment operations.increment(a, b, k) : Increment values from 'a' to 'b' by 'k'. After m operations, we need to calculate the maximum of the values in the array.Examples:Input : n = 5 m = 3 a = 0, b
10 min read