Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Program to find maximum value by inserting operators in between numbers in Python
When given a list of numbers, we need to find the maximum value possible by inserting binary operators (+, -, *) and parentheses between them. This problem uses dynamic programming to explore all possible combinations of operations.
For example, with nums = [-6, -4, -10], we can create the expression ((-6) + (-4)) * -10 = (-10) * (-10) = 100.
Algorithm Steps
The solution uses a recursive approach with memoization:
For each subarray, calculate both minimum and maximum possible values
Try all possible split points and operators
Combine results from left and right subarrays
Track the highest value found
Implementation
import operator
class Solution:
def solve(self, nums):
ops = [operator.add, operator.sub, operator.mul]
n = len(nums)
# Handle edge case - all zeros
if not any(nums):
return 0
def dp(i, j):
# Base case - single number
if i == j:
return [nums[i], nums[i]]
low = float("inf")
high = float("-inf")
# Try all possible split points
for k in range(i, j):
left_results = dp(i, k)
right_results = dp(k + 1, j)
# Try all combinations of left and right results with each operator
for left_val in left_results:
for right_val in right_results:
for op in ops:
result = op(left_val, right_val)
low = min(low, result)
high = max(high, result)
return [low, high]
# Return the maximum value possible
return dp(0, n - 1)[1]
# Test the solution
solution = Solution()
nums = [-6, -4, -10]
result = solution.solve(nums)
print(f"Input: {nums}")
print(f"Maximum value: {result}")
Input: [-6, -4, -10] Maximum value: 100
How It Works
The algorithm recursively divides the array and tries all possible ways to combine subarrays:
Base case: Single number returns itself as both min and max
Recursive case: Split array at each position and try all operators
Combination: Apply each operator to all possible value pairs from left and right subarrays
Tracking: Keep track of minimum and maximum values to handle negative numbers correctly
Example Walkthrough
For [-6, -4, -10], one optimal split is:
# Step-by-step calculation
nums = [-6, -4, -10]
# Split: [-6, -4] and [-10]
# Left part: -6 + (-4) = -10 or -6 - (-4) = -2 or -6 * (-4) = 24
# Right part: -10
# Final combinations:
# -10 * (-10) = 100 ? Maximum value
# -2 * (-10) = 20
# 24 + (-10) = 14
# etc.
print("Optimal expression: ((-6) + (-4)) * (-10) = 100")
Optimal expression: ((-6) + (-4)) * (-10) = 100
Conclusion
This dynamic programming solution explores all possible parenthesizations and operator combinations to find the maximum value. The key insight is tracking both minimum and maximum values at each step since negative numbers can become positive when multiplied.
