
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
Maximum path sum in an Inverted triangle in C++
In this problem, we are given numbers in the form of an inverted triangle. Our task is to create a program that will find the maximum path sum in an inverted triangle.
Inverted triangle form of number is an arrangement when the first row contains n elements, second n-1, and so on.
Here, we have to find the maximum sum that can 3 be obtained by adding one element from each row.
Let’s take an example to understand the problem −
Input −
5 1 9 3 6 2
Output − 17
Explanation − Here, I have found the path from the last row to the top row, considering the maximum possible elements in the path.
To solve this problem, we will be using the dynamic programming approach, similar to what we apply in the case of minimum cost path problems. Here, we will start from the bottom and then find the path the gives the maximum sum.
Prior to this we will consider the inverted triangle as a regular matrix by shift all number of left and add 0’s to the remaining places.
Example
Program to find the maximum path sum in an inverted triangle −
#include <iostream> using namespace std; #define N 3 int findMaxPathSumInvertedTriangle(int matrix[][N]){ int maxSum = 0; for (int i = N - 2; i >= 0; i--) { for (int j = 0; j < N - i; j++) { if (j - 1 >= 0) matrix[i][j] += max(matrix[i + 1][j], matrix[i + 1][j - 1]); else matrix[i][j] += matrix[i + 1][j]; maxSum = max(maxSum, matrix[i][j]); } } return maxSum; } int main(){ int invertedTriangle[N][N] = { {5, 1, 9}, {3, 6, 0}, {2, 0, 0}}; cout<<"The maximum path sum is "<<findMaxPathSumInvertedTriangle(invertedTriangle); return 0; }
Output
The maximum path sum is 17
- Related Articles
- Maximum path sum in a triangle in C++
- Maximum sum of a path in a Right Number Triangle in C++
- Maximum path sum in matrix in C++
- Binary Tree Maximum Path Sum in Python
- Minimum Sum Path in a Triangle in C++
- Maximum Sum Path in Two Arrays in C++
- Maximum Path Sum in a Binary Tree in C++
- Maximum sum path in a matrix from top to bottom in C++
- Maximum sum path in a matrix from top to bottom in C++ Program
- Maximum path sum for each position with jumps under divisibility condition in C++
- Path Sum in Python
- Maximum equlibrium sum in an array in C++
- Maximum sum path in a matrix from top to bottom and back in C++ Program
- Path with Maximum Gold in C++
- Sum triangle from an array in C programming
