Last active
December 28, 2015 02:09
-
-
Save ptsurko/7425452 to your computer and use it in GitHub Desktop.
Solution for http://habrahabr.ru/post/200190/
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
namespace TwitterTest | |
{ | |
public class Solver | |
{ | |
private readonly int[] _walls; | |
public Solver(int[] walls) | |
{ | |
_walls = walls; | |
} | |
public int Solve() | |
{ | |
var result = 0; | |
var stack = new Stack<Wall>(); | |
for (var i = 0; i < _walls.Length; i++) | |
{ | |
var currentWaterHeight = 0; | |
if (stack.Count > 0 && _walls[i] > stack.Peek().Height) | |
{ | |
while (stack.Count > 0) | |
{ | |
var wall = stack.Peek(); | |
result += (i - wall.Index - 1) * Math.Abs(Math.Min(wall.Height, _walls[i]) - currentWaterHeight); | |
if (wall.Height <= _walls[i]) | |
{ | |
stack.Pop(); | |
currentWaterHeight = wall.Height; | |
} | |
else | |
{ | |
break; | |
} | |
} | |
} | |
stack.Push(new Wall(i, _walls[i])); | |
} | |
return result; | |
} | |
private class Wall | |
{ | |
public Wall(int index, int height) | |
{ | |
Index = index; | |
Height = height; | |
} | |
public int Index { get; private set; } | |
public int Height { get; private set; } | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using NUnit.Framework; | |
namespace TwitterTest | |
{ | |
[TestFixture] | |
public class SolverTests | |
{ | |
[Test] | |
public void Test1() | |
{ | |
var array = new[] {2, 5, 1, 2, 3, 4, 7, 7, 6}; | |
var solver = new Solver(array); | |
var result = solver.Solve(); | |
Assert.That(result, Is.EqualTo(10)); | |
} | |
[Test] | |
public void Test2() | |
{ | |
var array = new[] { 2, 5, 1, 3, 1, 2, 1, 7, 7, 6 }; | |
var solver = new Solver(array); | |
var result = solver.Solve(); | |
Assert.That(result, Is.EqualTo(17)); | |
} | |
[Test] | |
public void Test3() | |
{ | |
var array = new[] {1, 2, 3, 4, 5}; | |
var solver = new Solver(array); | |
var result = solver.Solve(); | |
Assert.That(result, Is.EqualTo(0)); | |
} | |
[Test] | |
public void Test4() | |
{ | |
var array = new[] { 1, 0, 0, 0, 1, 2 }; | |
var solver = new Solver(array); | |
var result = solver.Solve(); | |
Assert.That(result, Is.EqualTo(3)); | |
} | |
[Test] | |
public void Test5() | |
{ | |
var array = new[] { 1, 0, 0, 5, 3, 5, 0, 1, 2 }; | |
var solver = new Solver(array); | |
var result = solver.Solve(); | |
Assert.That(result, Is.EqualTo(7)); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment