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.
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) = 33 Input : 5 -3 -5 2 3 9 4 Output : 62
This problem can be solved by using dynamic programming.
- Assuming 2D array dp of dimensions n * 2.
- dp[i] represents the maximum value of the array up to ith position if the last operation is addition.
- dp[i] 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] = max(dp[ i - 1], dp[ i - 1]) + a[ i + 1]; dp[i] = dp[i - 1] - a[i] + a[i] * a[i + 1];
The base cases are:
dp = a + a; dp = a * a;
Below is the implementation of the above approach:
- Arrange the array such that upon performing given operations an increasing order is obtained
- Maximum sum of all elements of array after performing given operations
- Maximum Possible Product in Array after performing given Operations
- Maximum score possible after performing given operations on an Array
- Maximum count of equal numbers in an array after performing given operations
- Find the final sequence of the array after performing given operations
- Check if at least half array is reducible to zero by performing some operations
- Number of array elements derivable from D after performing certain operations
- Find the modified array after performing k operations of given type
- Number of elements from the array which are reachable after performing given operations on D
- Minimum element left from the array after performing given operations
- Maximum array sum that can be obtained after exactly k changes
- Find the final number obtained after performing the given operation
- Maximum possible array sum after performing the given operation
- Find maximum points which can be obtained by deleting elements from array
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.
Improved By : AnkitRai01