Minimum number of steps to convert a given matrix into Upper Hessenberg matrix
Last Updated :
19 Dec, 2022
Given a matrix of order NxN, Find the minimum number of steps to convert the given matrix into the Upper Hessenberg matrix. In each step, the only operation allowed is to decrease or increase any element value by 1.
Examples:
Input : N=3
1 2 8
1 3 4
2 3 4
Output :2
Decrease the element a[2][0] 2 times.
Now the matrix is upper hessenberg
Input : N=4
1 2 2 3
1 3 4 2
3 3 4 2
-1 0 1 4
Output :4
Approach:
- For a matrix to be an Upper Hessenberg matrix all of its elements below the sub-diagonal must be equal to zero, i.e Aij = 0 for all i > j+1..
- The minimum number of steps required to convert a given matrix in the upper Hessenberg matrix is equal to the sum of the absolute values of all Aij for all i > j + 1.
- The modulus value of the element is taken into account because both the increase and decrease of the element count as a single step.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
#define N 4
using namespace std;
int stepsRequired( int arr[][N])
{
int result = 0;
for ( int i = 0; i < N; i++) {
for ( int j = 0; j < N; j++) {
if (i > j + 1)
result += abs (arr[i][j]);
}
}
return result;
}
int main()
{
int arr[N][N] = { 1, 2, 3, 4,
3, 1, 0, 3,
3, 2, 1, 3,
-3, 4, 2, 1 };
cout << stepsRequired(arr);
return 0;
}
|
Java
class GFG
{
static int N = 4 ;
static int stepsRequired( int arr[][])
{
int result = 0 ;
for ( int i = 0 ; i < N; i++)
{
for ( int j = 0 ; j < N; j++)
{
if (i > j + 1 )
result += Math.abs(arr[i][j]);
}
}
return result;
}
public static void main (String[] args)
{
int arr [][] = new int [][] {{ 1 , 2 , 3 , 4 },
{ 3 , 1 , 0 , 3 },
{ 3 , 2 , 1 , 3 },
{- 3 , 4 , 2 , 1 }};
System.out.println(stepsRequired(arr));
}
}
|
Python3
N = 4 ;
def stepsRequired(arr):
result = 0 ;
for i in range (N):
for j in range (N):
if (i > j + 1 ):
result + = abs (arr[i][j]);
return result;
arr = [[ 1 , 2 , 3 , 4 ],
[ 3 , 1 , 0 , 3 ],
[ 3 , 2 , 1 , 3 ],
[ - 3 , 4 , 2 , 1 ]];
print (stepsRequired(arr));
|
C#
using System;
class GFG
{
static int N = 4;
static int stepsRequired( int [, ] arr)
{
int result = 0;
for ( int i = 0; i < N; i++)
{
for ( int j = 0; j < N; j++)
{
if (i > j + 1)
result += Math.Abs(arr[i, j]);
}
}
return result;
}
public static void Main ()
{
int [ , ] arr = new int [, ] { {1, 2, 3, 4},
{3, 1, 0, 3},
{3, 2, 1, 3},
{-3, 4, 2, 1}};
Console.WriteLine(stepsRequired(arr));
}
}
|
Javascript
<script>
let N = 4;
function stepsRequired(arr)
{
let result = 0;
for (let i = 0; i < N; i++)
{
for (let j = 0; j < N; j++)
{
if (i > j + 1)
result += Math.abs(arr[i][j]);
}
}
return result;
}
let arr =[[1, 2, 3, 4],
[3, 1, 0, 3],
[3, 2, 1, 3],
[-3, 4, 2, 1 ]];
document.write(stepsRequired(arr));
</script>
|
Time complexity : O(N*N)
Auxiliary space: O(1) because it is using constant space for variables
Share your thoughts in the comments
Please Login to comment...