Problem from top coder (TCO 14 Round 1A DIV 1) and my solution

Problem:

Problem Statement

Manao is building a new house. He already purchased a rectangular area where he will place the house. The basement of the house should be built on a level ground, so Manao will have to level the entire area. The area is leveled if the difference between the heights of its lowest and highest square meter is at most 1. Manao wants to measure the effort he needs to put into ground leveling.You are given a String[] area. Each character in area denotes the height at the corresponding square meter of Manao’s area. Using 1 unit of effort, Manao can change the height of any square meter on his area by 1 up or down. Return the minimum total effort he needs to put to obtain a leveled area.

Definition

Class: HouseBuilding
Method: getMinimum
Parameters: String[]
Returns: int
Method signature: int getMinimum(String[] area)
(be sure your method is public)

My Code:

public class HouseBuilding
{
public int getMinimum(String[] area)
{
int min = 11;
int max = -1;

int[] c = new int[10];

for(int i = 0; i < area.length; i++)
{
for(int j = 0; j < area[i].length();j++)
{
int val = Integer.parseInt(“” + area[i].charAt(j));
c[val]++;
if(val > max)
max = val;
if(val < min)
min = val;
}
}

if(max – min <= 1)
return 0;

int result = Integer.MAX_VALUE;
for(int i = 0; i < 9; i++)
{
int sum = 0;
for(int j = 0; j < 10; j++)
{
if( j <= i)
{
sum += (i – j) * c[j];
}
else
sum += (j – i -1) * c[j];
}

if(sum < result)
result = sum;
}

for(int i = 0; i < 9; i++)
{
int sum = 0;
for(int j = 0; j < 10; j++)
{
if( j <= i)
{
sum += (i – j) * c[j];
}
else
sum += (j – i) * c[j];
}

if(sum < result)
result = sum;
}

return result;
}
}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s