Given a n*m grid and the position of some poles to be painted in the grid, the task is to find the minimum cost to paint all the poles. There is no cost involved in moving from one row to the other, whereas moving to an adjacent column has 1 rupee cost associated with it.
Examples:
Input: n = 2, m = 2, noOfPos = 2
pos[0] = 0, 0
pos[1] = 0, 1
Output: 1
The grid is of 2*2 size and there are two poles at {0, 0} and {0, 1}.
So we will start at {0, 0} and paint the pole and then go to
the next column to paint the pole at {0, 1} position which will
cost 1 rupee to move one column.
Input: n = 2, m = 2, noOfPos = 2
pos[0] = {0, 0}
pos[1] = {1, 0}
Output: 0
Both poles are in the same column. So, no need to move to another column.
Approach: As there is the only cost of moving in columns, if we go to any column we will paint all the poles in that column and then move forward. So, basically, the answer will be the difference between the two farthest columns.
Below is the required implementation:
C++
#include <iostream>
#include <list>
using namespace std;
void find( int n, int m, int p, int q[2][2])
{
list < int > z ;
int i ;
for (i = 0;i < p;i++)
z.push_back(q[i][1]);
z.sort();
cout << z.back() - z.front() <<endl ;
}
int main()
{
int n = 2;
int m = 2;
int p = 2;
int q[2][2] = {{0,0},{0,1}} ;
find(n, m, p, q);
return 0;
}
|
Java
import java.util.*;
class solution
{
static void find( int n, int m, int p, int q[][])
{
Vector <Integer> z= new Vector<Integer>() ;
int i ;
for (i = 0 ;i < p;i++)
z.add(q[i][ 1 ]);
Collections.sort(z);
System.out.print(z.get(z.size()- 1 ) - z.get( 0 ) ) ;
}
public static void main(String args[])
{
int n = 2 ;
int m = 2 ;
int p = 2 ;
int q[][] = {{ 0 , 0 },{ 0 , 1 }} ;
find(n, m, p, q);
}
}
|
Python3
import math as ma
def find(n, m, p, q):
z = []
for i in range (p):
z.append(q[i][ 1 ])
print ( max (z) - min (z))
n, m, p = 2 , 2 , 2
q = [( 0 , 0 ), ( 0 , 1 )]
find(n, m, p, q)
|
C#
using System;
using System.Collections.Generic;
class GFG
{
static void find( int n, int m, int p, int [,]q)
{
List < int > z = new List< int >();
int i;
for (i = 0; i < p; i++)
z.Add(q[i, 1]);
z.Sort();
Console.Write(z[z.Count-1] - z[0]);
}
public static void Main(String []args)
{
int n = 2;
int m = 2;
int p = 2;
int [,]q = {{0, 0}, {0, 1}};
find(n, m, p, q);
}
}
|
PHP
<?php
function find( $n , $m , $p , $q )
{
$z = array ();
for ( $i = 0; $i < $p ; $i ++)
array_push ( $z , $q [ $i ][1]);
sort( $z );
echo max( $z ) - min( $z );
}
$n = 2;
$m = 2;
$p = 2;
$q = array ( array (0, 0),
array (0, 1));
find( $n , $m , $p , $q );
?>
|
Javascript
<script>
function find(n,m,p,q)
{
var z = [];
var i ;
for (i = 0;i < p;i++)
z.push(q[i][1]);
z.sort();
document.write( z[z.length-1] - z[0]);
}
var n = 2;
var m = 2;
var p = 2;
var q = [[0,0],[0,1]];
find(n, m, p, q);
</script>
|
Complexity Analysis:
- Time Complexity: O(plogp)
- Auxiliary Space: O(p)