Maximize arr[j] – arr[i] + arr[l] – arr[k], such that i < j < k < l in C++

C++Server Side ProgrammingProgramming

We are given with an array of integers. The goal is to maximize the value of expression −

arr[j]-arr[i] + arr[l]-arr[k] ; i<j<k<l indexes of elements

We will do so by traversing all elements and calculate the value of expression. If it is maximum found so far then store it and return in the end.

Input

arr[]= { 1,2,3,4 }

Output

Maximum value for above expression is : 2

Explanation − for i<j<k<l, i=0, j=1, k=2, l=3

arr[j]-arr[i]+arr[l]-arr[k]= 2-1+4-3=1+1=2

Input

arr[]= { 5,5,5,5,5 }

Output

Maximum value for above expression is : 0

Explanation − for i<j<k<l, for any value of i,j,k,l

arr[j]-arr[i]+arr[l]-arr[k]= 5-5+5-5=0

Approach used in the below program is as follows

  • Integer array a[] stores the numbers.

  • Function maximizeSum(int arr[], int n) takes array and its length n as input and returns maximum value of arr[j]-arr[i]+arr[l]-arr[k] such that i<j<k<l.

  • Variable sum is used to store the sum of arr[j]-arr[i] and arr[l]-arr[k].

  • Initialize maxx=arr[0] as initial maximum sum.

  • Traverse array from i=0, j=1,k=2, l=3 to i<n-3,j<n-2,k<n-1 and l<n

  • For each indexes in i,j,k,l compute arr[j]-arr[i]+arr[l]-arr[k] and store in sum

  • If current sum>=maxx update maxx.

  • In the end return maxx as desired result.

Example

 Live Demo

#include <bits/stdc++.h>
using namespace std;
// function to maximize the sum of selected numbers
int maximizeSum(int arr[], int n) {
   int sum=0;
   int maxx=arr[0];
   for(int i=0;i<n-3;i++)
      for(int j=i+1;j<n-2;j++)
         for(int k=j+1;k<n-1;k++)
         for(int l=k+1;l<n;l++){
      sum=arr[j]-arr[i]+arr[l]-arr[k];
      if(sum>=maxx)
         maxx=sum;
   }
   return maxx;
}
int main(){
   int a[] = {5, 3, 9, 2, 20};
   int n = sizeof(a) / sizeof(a[0]);
   cout <<"Maximized value is :"<< maximizeSum(a, n);
   return 0;
}

Output

Maximized value is :24
raja
Published on 28-Jul-2020 15:01:59
Advertisements