A Hackerrank Challenge: Given an NxN matrix, slice it and find the minimum slice
ID: 3920873 • Letter: A
Question
A Hackerrank Challenge:
Given an NxN matrix, slice it and find the minimum slice weight.
A slice consists of all the elements that are below, below right, or below left of the element above it. The Min Slice Weight is the minimum sum of all elements in the slice.
Example: given input
1 2 3
4 5 6
7 8 9
The slices would be 1 4 7; 1 4 8; 1 5 7; 1 5 8; 1 5 9; 2 4 7; 2 4 8; 2 5 8; 2 5 9;2 6 8; 2 6 9 ....etc.
The minimum slice would be 1 4 7 because 1+4+7 is the minimum of all the sums;
Write a function public int FindMinSlice (List<List<Integer>> Matrix) that returns the min slice weight.
NOTE: Psuedocode is accepted. I want to know the approach of solving this question.
Explanation / Answer
PseudoCode:
int FindMinSlice(list)
Step-I;
Declare MinimumSum variable and store the sum of first row i.e Matrix[0][0]+Matrix[0][1]+Matrix[0][2];
int minimumSum =Sum of First Row;
Step-2:
Now Iterate through every row.As we have
calulcated first row,start from 2nd row index is 1.
for(int i=1;i<(No:ofRows);i++){
sum=0;//initialise sum=0 for every loop
for(int j=0;j<(No:ofColumns);j++){
sum=sum +Matrix[i][j]; //caluclate sum of each number for a particular row
}
if(MinimumSum>sum){//After caluclating sum for each row caluclate here
MinimumSum=sum;//if sum variables is less than minimumSum,make it minimumSun
}
}
After iterating through all rows,MinimumSum
variable contains the minimumSum of slice of all slices.
return minimumSum variable
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.