Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Problems on Matrix
  • Practice Matrix
  • MCQs on Matrix
  • Tutorial on Matrix
  • Matrix Traversal
  • Sorting in Matrix
  • Matrix Rotation
  • Transpose of Matrix
  • Inverse of Matrix
  • Determinant of Matrix
  • Matrix Application
  • Adjoint & Inverse Matrix
  • Sparse Matrix
  • Matrix Exponentiation
Open In App
Next Article:
Maximum path sum in matrix
Next article icon

Find the maximum sum path in the given Matrix

Last Updated : 07 Nov, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

Consider an infinite matrix. The cells of the matrix are filled with natural numbers from the cell (1, 1) in the direction of top right to bottom left diagonally. Then the task is to output the Maximum path sum between two points (X1, Y1) and (X2, Y2).

Matrix filling process is as follows:

t1
Matrix filling process

Examples:

Input: X1 = 1, Y1 = 1, X2 = 3, Y2 = 3
Output: 32
Explanation: The best path for maximum sum for reaching (X2, Y2) from (X1, Y1) will be: 1 → 3 → 6 → 9 →13.

Input: X1 = 2, Y1 = 3, X2 = 4, Y2 = 5
Output: 97
Explanation: It can be verified that the maximum sum of the path will be 97.

Approach: Implement the idea below to solve the problem

The problem is observation based and can be solved using the precomputing the values of matrix then traversing in a greedy manner.

Steps were taken to solve the problem:

  • Initialize Variables: Create a StringBuilder let say SB for storing output. Also, define a 2D array let say XY[][] for storing the values of each cell in the matrix.
  • Precompute Cell Values: In the main() function, precompute the values of each cell in the matrix. The value of each cell is equal to the sum of its coordinates (X, Y). This can be done by iterating over all cells in the matrix and adding their values to XY[i][j].
  • Calculate Sum on Path: Calculate the maximum possible sum on a path from (X1, Y1) to (X2, Y2) by moving right and down in the precomputed matrix XY[][]. This can be done by adding up the values in all cells from (X1, Y1) to (X2, Y1), and then from (X2, Y1+1) to (X2, Y2).
  • Store Result: Append the calculated sum for each test case to the StringBuilder SB.
  • Print All Results: Print all results stored in SB.

Code to implement the approach:

C++
#include <iostream> #include <vector>  using namespace std; // Driver class int main() {     int N = 2005;     // Matrix for storing cell values     vector<vector<long long>> xy(N, vector<long long>(N));          long long start = 1LL;     // Precompute cell values     for (int i = 0; i < N; i++) {         int ti = 0, tj = i;         while (ti >= 0 && tj >= 0)             xy[ti++][tj--] = start++;     }     for (int i = 1; i < N; i++) {         int ti = i, tj = N - 1;         while (ti < N && tj < N)             xy[ti++][tj--] = start++;     }     // Define input coordinates     int x1 = 1, y1 = 1;     int x2 = 3, y2 = 3;     // Convert coordinates to 0-based indexing     x1--;     x2--;     y1--;     y2--;          long long s = xy[x2][y2];       // Calculate the sum along the path     while (x1 < x2)         s += xy[x1++][y1];     while (y1 < y2)         s += xy[x2][y1++];     // Print the result     cout << s << endl;          return 0; } 
Java
// Java code to implement the approach  import static java.lang.Math.*;  import java.util.*;  // Driver class public class Main {      // StringBuilder for storing output     static StringBuilder sb = new StringBuilder();      // Main Function     public static void main(String[] ScoobyDoobyDo)     {          // Size of the matrix (User defined)         int N = 2005;          // Matrix for storing cell values         xy = new long[N][N];          // Precompute cell values         long start = 1L;         for (int i = 0; i < N; i++) {             int ti = 0, tj = i;             while (ti >= 0 && tj >= 0)                 xy[ti++][tj--] = start++;         }         for (int i = 1; i < N; i++) {             int ti = i, tj = N - 1;             while (ti < N && tj < N)                 xy[ti++][tj--] = start++;         }          // Function call         solve();          // Print all results         System.out.println(sb);     }      static long[][] xy;      public static void solve()     {          // Inputs         int x1 = 1, y1 = 1;         int x2 = 3, y2 = 3;          // Changing to 0 based indexing         x1--;         x2--;         y1--;         y2--;          // Calculate sum on path from         // (x1, y1) to (x2, y2)         long s = xy[x2][y2];         while (x1 < x2)             s += xy[x1++][y1];         while (y1 < y2)             s += xy[x2][y1++];          // Append result to StringBuilder         sb.append(s + "\n");     } } 
Python
# Size of the matrix (User defined) N = 2005 # Matrix for storing cell values xy = [[0] * N for _ in range(N)] start = 1 # Precompute cell values for i in range(N):     ti, tj = 0, i     while ti >= 0 and tj >= 0:         xy[ti][tj] = start         start += 1         ti += 1         tj -= 1  for i in range(1, N):     ti, tj = i, N - 1     while ti < N and tj < N:         xy[ti][tj] = start         start += 1         ti += 1         tj -= 1 # Define input coordinates x1, y1 = 1, 1 x2, y2 = 3, 3 # Convert coordinates to 0-based indexing x1 -= 1 x2 -= 1 y1 -= 1 y2 -= 1  s = xy[x2][y2] # Calculate the sum along the path while x1 < x2:     s += xy[x1][y1]     x1 += 1  while y1 < y2:     s += xy[x2][y1]     y1 += 1 # Print the result print(s) 
C#
using System;  class Program {   // Driver class     static void Main(string[] args)     {           // Size of the matrix (User defined)         int N = 2005;           // Matrix for storing cell values         long[,] xy = new long[N, N];         long start = 1L;           // Precompute cell values         for (int i = 0; i < N; i++)         {             int ti = 0, tj = i;             while (ti >= 0 && tj >= 0)                 xy[ti++, tj--] = start++;         }         for (int i = 1; i < N; i++)         {             int ti = i, tj = N - 1;             while (ti < N && tj < N)                 xy[ti++, tj--] = start++;         }           //Inputs         int x1 = 1, y1 = 1;         int x2 = 3, y2 = 3;           // Changing to 0 based indexing         x1--;         x2--;         y1--;         y2--;           // Calculate sum on path from         // (x1, y1) to (x2, y2)         long s = xy[x2, y2];         while (x1 < x2)             s += xy[x1++, y1];         while (y1 < y2)             s += xy[x2, y1++];           //Print the results         Console.WriteLine(s);     } } 
JavaScript
// Size of the matrix (User defined) let N = 2005; // Matrix for storing cell values let xy = new Array(N); for (let i = 0; i < N; i++) {     xy[i] = new Array(N); } //Precompute the cell's value let start = 1n; for (let i = 0; i < N; i++) {     let ti = 0, tj = i;     while (ti >= 0 && tj >= 0) {         xy[ti++][tj--] = start++;     } } for (let i = 1; i < N; i++) {     let ti = i, tj = N - 1;     while (ti < N && tj < N) {         xy[ti++][tj--] = start++;     } } //Inputs let x1 = 1, y1 = 1; let x2 = 3, y2 = 3; // Changing to 0 based indexing x1--; x2--; y1--; y2--; // Calculate sum on path from // (x1, y1) to (x2, y2) let s = xy[x2][y2]; while (x1 < x2) {     s += xy[x1++][y1]; } while (y1 < y2) {     s += xy[x2][y1++]; } //Print the result console.log(s); 

Output
32

Time Complexity: O(N*M), Where N and M are nearly equivalent to X2 and Y2 respectively.
Auxiliary space: O(N*M)


Next Article
Maximum path sum in matrix
author
pradeep6036ymca
Improve
Article Tags :
  • Java
  • Matrix
  • Geeks Premier League
  • DSA
  • Arrays
  • DSA-Blogs
  • Geeks Premier League 2023
Practice Tags :
  • Arrays
  • Java
  • Matrix

Similar Reads

  • Maximise matrix sum by following the given Path
    Given a 2d-matrix mat[][] consisting of positive integers, the task is to find the maximum score we can reach if we have to go to cell mat[0][N - 1] starting from mat[0][0]. We have to cover the matrix in two phases: Phase 1: If we are at cell mat[i][j] then we can only go to cells mat[i][j + 1] or
    9 min read
  • Find sub-matrix with the given sum
    Given an N x N matrix and two integers S and K, the task is to find whether there exists a K x K sub-matrix with sum equal to S. Examples: Input: K = 2, S = 14, mat[][] = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 }, { 13, 14, 15, 16 }} Output: Yes 1 2 5 6 is the required 2 x 2 sub-matrix wit
    9 min read
  • Maximum sum path in a Matrix
    Given an n*m matrix, the task is to find the maximum sum of elements of cells starting from the cell (0, 0) to cell (n-1, m-1). However, the allowed moves are right, downwards or diagonally right, i.e, from location (i, j) next move can be (i+1, j), or, (i, j+1), or (i+1, j+1). Find the maximum sum
    15+ min read
  • Maximum path sum in matrix
    Given a matrix of size n * m. Find the maximum path sum in the matrix. The maximum path is the sum of all elements from the first row to the last row where you are allowed to move only down or diagonally to left or right. You can start from any element in the first row. Examples: Input: mat[][] = 10
    6 min read
  • Find row with maximum sum in a Matrix
    Given an N*N matrix. The task is to find the index of a row with the maximum sum. That is the row whose sum of elements is maximum. Examples: Input : mat[][] = { { 1, 2, 3, 4, 5 }, { 5, 3, 1, 4, 2 }, { 5, 6, 7, 8, 9 }, { 0, 6, 3, 4, 12 }, { 9, 7, 12, 4, 3 }, }; Output : Row 3 has max sum 35 Input :
    11 min read
  • Pair with maximum sum in a Matrix
    Given a NxM matrix with N rows and M columns of positive integers. The task is to find the sum of pair with maximum sum in the matrix. Examples: Input : mat[N][M] = {{1, 2, 3, 4}, {25, 6, 7, 8}, {9, 10, 11, 12}, {13, 14, 15, 16}} Output : 41 Pair (25, 16) has the maximum sum Input : mat[N][M] = {{1,
    7 min read
  • Maximum sum path in a matrix from top to bottom
    Consider a n*n matrix. Suppose each cell in the matrix has a value assigned. We can go from each cell in row i to a diagonally higher cell in row i+1 only [i.e from cell(i, j) to cell(i+1, j-1) and cell(i+1, j+1) only]. Find the path from the top row to the bottom row following the aforementioned co
    15 min read
  • Program to find the maximum element in a Matrix
    Given an NxM matrix. The task is to find the maximum element in this matrix. Examples: Input: mat[4][4] = {{1, 2, 3, 4}, {25, 6, 7, 8}, {9, 10, 11, 12}, {13, 14, 15, 16}}; Output: 25 Input: mat[3][4] = {{9, 8, 7, 6}, {5, 4, 3, 2}, {1, 0, 12, 45}}; Output: 45 Approach: The idea is to traverse the mat
    6 min read
  • Find the length of maximum path in given matrix for each index
    Given a binary square matrix of characters having size N x N such that 1 represents land and 0 represents water, the task is to find the longest straight-line path a person can travel on land without falling into water or outside for each cell (i, j). The straight line can be either horizontal, vert
    15+ min read
  • Maximum Path Sum in a Binary Tree
    Given a binary tree, the task is to find the maximum path sum. The path may start and end at any node in the tree. Example: Input: Output: 42Explanation: Max path sum is represented using green colour nodes in the above binary tree. Input: Output: 31Explanation: Max path sum is represented using gre
    9 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences