Thursday 25 June 2015

CODILITY - LESSON 5 - StoneWall

THE PROBLEM:
You are going to build a stone wall. The wall should be straight and N meters long, and its thickness should be constant; however, it should have different heights in different places. The height of the wall is specified by a zero-indexed array H of N positive integers. H[I] is the height of the wall from I to I+1 meters to the right of its left end. In particular, H[0] is the height of the wall's left end and H[N−1] is the height of the wall's right end.
The wall should be built of cuboid stone blocks (that is, all sides of such blocks are rectangular). Your task is to compute the minimum number of blocks needed to build the wall.
Write a function:
class Solution { public int solution(int[] H); }
that, given a zero-indexed array H of N positive integers specifying the height of the wall, returns the minimum number of blocks needed to build it.
For example, given array H containing N = 9 integers:
  H[0] = 8    H[1] = 8    H[2] = 5
  H[3] = 7    H[4] = 9    H[5] = 8
  H[6] = 7    H[7] = 4    H[8] = 8
the function should return 7. The figure shows one possible arrangement of seven blocks.

THEIR SOLUTION:

class Solution {
    public int solution(int[] H) {
        // write your code in C# 6.0 with .NET 4.5 (Mono)
      
        int L = H.Length;
        int stones =0;
        int [] wall = new int [L];
        int wallNum=0;
        
        for (int i=0; i<L; i++)
        {
            while (wallNum>0 && wall[wallNum-1] > H[i]) wallNum -=1;   
            if (wallNum >0 && wall[wallNum -1] == H[i]) continue;
            else 
                {
                    stones +=1;
                    wall[wallNum] = H[i];
                    wallNum +=1;     
                }
        }
        return stones;
    }

}

It took me forever to understand the problem, and then it took me forever to come up with a solution that didn't fully work. I ended up checking their blog to see if the problem was better explained and then I read their solution and just couldn't take it off my mind. So I re wrote it in C#. Then it was just too late to come up with something completely mine! (specially because I didn't like the problem)

PR


No comments:

Post a Comment