703437. Maximum possible sum
Medium
Maximum possible sum Slug: maximum-possible-sum4134 Difficulty: Medium Id: 703437 Topic Tags: Arrays, Hash, Data Structures Company Tags: None
Summary
Given an array of integers, find the maximum possible sum that can be obtained by performing a series of operations: adding or subtracting any number from the array. The goal is to maximize the total sum.
Detailed Explanation
To solve this problem, we need to consider all possible combinations of adding and subtracting numbers from the array and keep track of the maximum sum. We can use a dynamic programming approach to achieve this.
Here's a step-by-step breakdown of the solution:
- Initialize two arrays
max_sumandmin_sumwith the same size as the input array, both initialized with zeros. - Iterate through the input array:
- For each element in the array, calculate the maximum sum by adding or subtracting the current element from the previous maximum sum (if it's positive) or minimum sum (if it's negative).
- Update
max_sumandmin_sumaccordingly.
- The maximum possible sum is stored in
max_sum[0], which represents the maximum sum that can be obtained by performing all operations.
Time complexity: O(n), where n is the size of the input array. Space complexity: O(n), as we need to store the dynamic programming arrays.
Optimized Solutions
Java
public class Main {
public static int maxPossibleSum(int[] arr) {
int n = arr.length;
int[] max_sum = new int[n];
int[] min_sum = new int[n];
max_sum[0] = arr[0];
min_sum[0] = arr[0];
for (int i = 1; i < n; i++) {
max_sum[i] = Math.max(max_sum[i-1], arr[i]);
min_sum[i] = Math.min(min_sum[i-1], arr[i]);
if (arr[i] > 0) {
max_sum[i] += arr[i];
min_sum[i] -= arr[i];
} else {
max_sum[i] += arr[i];
min_sum[i] -= arr[i];
}
}
return Math.max(max_sum[n-1], -min_sum[n-1]);
}
}