Maximize array elements up to given numbers in C++

C++Server Side ProgrammingProgramming

Problem statement

Given an array of integers, a number and a maximum value, the task is to compute the maximum value that can be obtained from the array elements. Every value on the array traversing from the beginning can be either added to or subtracted from the result obtained from the previous index such that at any point the result is not less than 0 and not greater than the given maximum value. For index 0 take the previous result equal to the given number. In case of no possible answer print -1.

If arr[] = {3, 10, 6, 4, 5}, number = 1 and max value = 15 then output would be 9 if follow below order of addition and subtraction −

1 + 3 + 10 – 6 – 4 + 5

Algorithm

We can use a recursive approach to solve this problem

1. At every index position there are two choices, either add current array element to value obtained so far from previous elements or subtract current array element from value obtained so far from previous elements
2. Start from index 0, add or subtract arr[0] from given number and recursively call for next index along with updated number
3. When entire array is traversed, compare the updated number with overall maximum value of number obtained so far

Example

 Live Demo

#include <bits/stdc++.h>
using namespace std;
void getMaxValue(int *arr, int n, int num, int maxLimit, int
idx, int& result){
   if (idx == n) {
      result = max(result, num);
      return;
   }
   if (num - arr[idx] >= 0) {
      getMaxValue(arr, n, num - arr[idx], maxLimit, idx + 1, result);
   }
   if (num + arr[idx] <= maxLimit) {
      getMaxValue(arr, n, num + arr[idx], maxLimit, idx + 1, result);
   }
}
int getMaxValue(int *arr, int n, int num, int maxLimit){
   int result = 0;
   int idx = 0;
   getMaxValue(arr, n, num, maxLimit, idx, result);
   return result;
}
int main(){
   int num = 1;
   int arr[] = {3, 10, 6, 4, 5};
   int n = sizeof(arr) / sizeof(arr[0]);
   int maxLimit = 15;
   cout << "Maximum value = " << getMaxValue(arr, n, num, maxLimit) << endl;
   return 0;
}

Output

When you compile and execute the above program. It generates the following output−

Maximum value = 9
raja
Published on 24-Dec-2019 06:45:23
Advertisements