Skip to content

Instantly share code, notes, and snippets.

@alikrc
Created February 1, 2021 21:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alikrc/9808137f0279ab0e56c77150b906e2db to your computer and use it in GitHub Desktop.
Save alikrc/9808137f0279ab0e56c77150b906e2db to your computer and use it in GitHub Desktop.
using System;
using System.Collections.Generic;
class Solution
{
public int solution(int[] A)
{
var numberOfVariations = 0;
var alreadyCut = false;
for (int i = 0; i + 2 < A.Length; i++)
{
var firstHeight = A[i];
var secondHeight = A[i + 1];
var thirdHeight = A[i + 2];
var gradient1 = firstHeight.CompareTo(secondHeight);
var gradient2 = secondHeight.CompareTo(thirdHeight);
if (gradient1 == 0)
{
if (alreadyCut)
{
return -1;
}
alreadyCut = true;
numberOfVariations += 2;
}
if (gradient2 == 0)
{
if (alreadyCut)
{
return -1;
}
alreadyCut = true;
numberOfVariations += 2;
}
if (gradient1 == gradient2)
{
if (alreadyCut)
{
return -1;
}
alreadyCut = true;
var isRestOfArrayAestheticallyPleasing = IsAestheticallyPleasing(A, i + 4);
int? fourthHeight = null;
//if fourth not exists
if (i + 3 < A.Length)
{
fourthHeight = A[i + 3];
//cut third tree and find if possible
bool isThirdTreeCutSuitsTheRule = IsAestheticallyPleasing(firstHeight, secondHeight, fourthHeight);
if (isRestOfArrayAestheticallyPleasing & isThirdTreeCutSuitsTheRule)
{
numberOfVariations++;
}
}
//cut first tree and find if possible
bool isFirstTreeCutSuitsTheRule = IsAestheticallyPleasing(secondHeight, thirdHeight, fourthHeight);
//cut second tree and find if possible
bool isSecondTreeCutSuitsTheRule = IsAestheticallyPleasing(firstHeight, thirdHeight, fourthHeight);
if (isRestOfArrayAestheticallyPleasing & isFirstTreeCutSuitsTheRule)
{
numberOfVariations++;
}
if (isRestOfArrayAestheticallyPleasing & isSecondTreeCutSuitsTheRule)
{
numberOfVariations++;
}
}
}
return numberOfVariations;
}
private bool IsAestheticallyPleasing(int firstHeight, int secondHeight)
{
var gradient = firstHeight.CompareTo(secondHeight);
if (gradient != 0)
{
return true;
}
return false;
}
private bool IsAestheticallyPleasing(int firstHeight, int secondHeight, int? thirdHeight)
{
if (thirdHeight.HasValue == false)
{
return IsAestheticallyPleasing(firstHeight, secondHeight);
}
var gradient1 = firstHeight.CompareTo(secondHeight);
var gradient2 = secondHeight.CompareTo(thirdHeight);
if (gradient1 != gradient2 && gradient1 != 0 && gradient2 != 0)
{
return true;
}
return false;
}
private bool IsAestheticallyPleasing(int[] arr, int indexToStart)
{
for (int i = indexToStart; i + 2 < arr.Length; i++)
{
var firstHeight = arr[i];
var secondHeight = arr[i + 1];
var thirdHeight = arr[i + 2];
if (!IsAestheticallyPleasing(firstHeight, secondHeight, thirdHeight))
{
return false;
}
}
return true;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment