# Maximum Sum Increasing Subsequence using Binary Indexed Tree in C++ program

C++Server Side ProgrammingProgramming

In this problem, we are given an array arr[] of n integers. Our task is to create a program to find the maximum sum increasing subsequence using binary indexed tree in C++.

Problem Description − We need to find an increasing subsequence with the maximum sum using the elements of the array.

Increasing Subsequence − subsequence in which the value of the current element is greater than the element at the previous position.

Binary Indexed Tree − It is a data structure which is a type of tree. We can add or remove elements from the tree in an effective way.

Let’s take an example to understand the problem,

## Input

arr[] = {5, 1, 7, 3, 8, 2}

## Output

20

## Explanation

Subsequences:
{5, 7, 8} = 5 + 7 + 8 = 20
{1, 3, 8} = 1 + 3 + 8 = 12
{1, 7, 8} = 1 + 7 + 8 = 16

## Solution Approach

In this problem, we need to find the maxSum possible by using a binary index tree. For this, we will create a binary index tree using a map from elements of the array. Then using the elements of the array by iterating, for each element we need to find the sum of all elements till the value in the BIT. And then return the maximum sum of all values.

## Example

Program to illustrate the working of our solution,

Live Demo

#include <bits/stdc++.h>
using namespace std;
int calcMaxSum(int BITree[], int index){
int sum = 0;
while (index > 0) {
sum = max(sum, BITree[index]);
index −= index & (−index);
}
return sum;
}
void updateTreeVal(int BITree[], int newIndex, int index, int sumVal){
while (index <= newIndex) {
BITree[index] = max(sumVal, BITree[index]);
index += index & (−index);
}
}
int calcMaxSumBIT(int arr[], int n){
int uniqCount = 0, maxSum;
map<int, int> BinaryIndexTree;
for (int i = 0; i < n; i++) {
BinaryIndexTree[arr[i]] = 0;
}
for (map<int, int>::iterator it = BinaryIndexTree.begin();
it != BinaryIndexTree.end(); it++) {
uniqCount++;
BinaryIndexTree[it−>first] = uniqCount;
}
int* BITree = new int[uniqCount + 1];
for (int i = 0; i <= uniqCount; i++) {
BITree[i] = 0;
}
for (int i = 0; i < n; i++) {
maxSum = calcMaxSum(BITree, BinaryIndexTree[arr[i]] − 1);
updateTreeVal(BITree, uniqCount, BinaryIndexTree[arr[i]],
maxSum + arr[i]);
}
return calcMaxSum(BITree, uniqCount);
}
int main(){
int arr[] = {5, 1, 7, 3, 8, 2};
int n = sizeof(arr) / sizeof(arr[0]);
cout<<"The maximum sum increasing subsequence using binary
indexed tree is "<<calcMaxSumBIT(arr, n);
return 0;
}

## Output

The maximum sum increasing subsequence using binary indexed tree is 20
Published on 09-Dec-2020 13:12:59