- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Path with smallest sum in JavaScript
Problem
JavaScript function that takes in a 2-D array of numbers as the first and the only argument.
Our function should find paths from the 2-D array by picking exactly one element from each row, and no two elements picked from adjacent rows should be in the same column. Out of all these paths, our function should return the sum of that path that has the minimum sum.
For example, if the input to the function is −
const arr = [ [4, 7, 1], [2, 8, 3], [5, 6, 9] ]
Then the output should be −
const output = 9;
Output Explanation
Because all the valid paths are −
4, 8, 9 | 4, 8, 6 | 4, 3, 6 | 4, 3, 5 |
7, 2, 6 | 7, 2, 9 | 7, 3, 6 | 7, 3, 5 |
1, 2, 6 | 1, 2, 9 | 1, 8, 9 | 1, 8, 5 |
And out of these all, [1, 2, 6] has the least sum of 9.
Example
The code for this will be −
const arr = [ [4, 7, 1], [2, 8, 3], [5, 6, 9] ] const minimumPathSum = (arr = []) => { let first = [0, null]; let second = [0, null]; for(let row = arr.length - 1; row >= 0; row--){ let curr1 = null; let curr2 = null; for(let column = 0; column < arr[row].length; column++){ let currentSum = arr[row][column]; if(column !== first[1]){ currentSum += first[0]; }else{ currentSum += second[0]; }; if(curr1 === null || currentSum < curr1[0]){ curr2 = curr1; curr1 = [currentSum, column]; }else if(curr2 === null || currentSum < curr2[0]){ curr2 = [currentSum, column]; }; }; first = curr1; second = curr2; }; return first[0]; }; console.log(minimumPathSum(arr));
Output
And the output in the console will be −
9
- Related Articles
- Greatest sum and smallest index difference in JavaScript
- Finding smallest sum after making transformations in JavaScript
- Removing smallest subarray to make array sum divisible in JavaScript
- Checking digit sum of smallest number in the array in JavaScript
- Path Sum in Python
- Minimum Path Sum in C++
- Path Sum III in C++
- Minimum Path Sum in Python
- Path Sum IV in C++
- Minimum Falling Path Sum in C++
- Program to find length of longest path with even sum in Python
- Maximum sum of smallest and second smallest in an array in C++
- Smallest positive value that cannot be represented as sum of subarray JavaScript
- Maximum path sum in matrix in C++
- Triplet with desired sum in JavaScript

Advertisements