Maximum path sum for each position with jumps under divisibility condition in C++


In this tutorial, we will be discussing a program to find maximum path sum for each position with jumps under divisibility condition

For this we will be provided with an array of n random integers. Our task is to jump from one position to another if it divides it and finally provide the maximum sum path for every given position.

Example

 Live Demo

#include <bits/stdc++.h>
using namespace std;
//finding maximum sum path
void printMaxSum(int arr[], int n) {
   int dp[n];
   memset(dp, 0, sizeof dp);
   for (int i = 0; i < n; i++) {
      dp[i] = arr[i];
      int maxi = 0;
      for (int j = 1; j <= sqrt(i + 1); j++) {
         if (((i + 1) % j == 0) && (i + 1) != j) {
            if (dp[j - 1] > maxi)
               maxi = dp[j - 1];
            if (dp[(i + 1) / j - 1] > maxi && j != 1)
               maxi = dp[(i + 1) / j - 1];
         }
      }
      dp[i] += maxi;
   }
   for (int i = 0; i < n; i++)
      cout << dp[i] << " ";
}
int main() {
   int arr[] = { 2, 3, 1, 4, 6, 5 };
   int n = sizeof(arr) / sizeof(arr[0]);
   printMaxSum(arr, n);
   return 0;
}

Output

2 5 3 9 8 10

Updated on: 09-Sep-2020

47 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements