Ways to paint stairs with two colors such that two adjacent are not yellow
Last Updated :
26 Apr, 2021
Given n stairs and we have 2 colour yellow and green the task is that we have to paint given stairs by given colour with condition is that we cannot paints two yellow steps directly after each other.
Examples :
Input : n = 1
Output : 2
A single stair can be colored either
as green or yellow.
Input : n = 3
Output : 5
Case 1: When we have 1 stair, we can paint either yellow or green.
Case 2: When we have 2 stairs, we can paint first stair by either yellow or green but for next stair we can only paint by green because we cannot paint two yellow steps directly after each other. So total cases are three YG, GG, GY.
Case 3: When we have 3 stairs then we can paint it by in 5 ways.
If we take a closer look, we can notice that it follows Fibonacci Series.
C++
#include <bits/stdc++.h>
using namespace std;
int ways( int n)
{
int W[n + 1];
W[1] = 2;
W[2] = 3;
for ( int i = 3; i <= n; i++)
W[i] = W[i - 1] + W[i - 2];
return W[n];
}
int main()
{
int n = 3;
printf ( "%d" , ways(n));
return 0;
}
|
Java
import java.io.*;
public class GFG {
static int ways( int n)
{
int []W = new int [n+ 1 ];
W[ 1 ] = 2 ;
W[ 2 ] = 3 ;
for ( int i = 3 ; i <= n; i++)
W[i] = W[i - 1 ] + W[i - 2 ];
return W[n];
}
static public void main (String[] args)
{
int n = 3 ;
System.out.println(ways(n));
}
}
|
Python3
def ways( n ):
W = list ()
W.append( 0 )
W.append( 2 )
W.append( 3 )
i = 3
while i < = n:
W.append(W[i - 1 ] + W[i - 2 ])
i = i + 1
return W[n]
n = 3
print (ways(n))
|
C#
using System;
public class GFG {
static int ways( int n)
{
int []W = new int [n+1];
W[1] = 2;
W[2] = 3;
for ( int i = 3; i <= n; i++)
W[i] = W[i - 1] + W[i - 2];
return W[n];
}
static public void Main ()
{
int n = 3;
Console.WriteLine(ways(n));
}
}
|
PHP
<?php
function ways( $n )
{
$W [1] = 2;
$W [2] = 3;
for ( $i = 3; $i <= $n ; $i ++)
$W [ $i ] = $W [ $i - 1] +
$W [ $i - 2];
return $W [ $n ];
}
$n = 3;
echo ways( $n );
?>
|
Javascript
<script>
function ways(n)
{
let W = [];
W[1] = 2;
W[2] = 3;
for (let i = 3; i <= n; i++)
W[i] = W[i - 1] + W[i - 2];
return W[n];
}
let n = 3;
document.write(ways(n));
</script>
|
Output :
5
Time Complexity : O(n)
Extra Space : O(n)
We can solve this problem in O(Log n) time also using matrix exponentiation solution for n-th Fibonacci Number.
Share your thoughts in the comments
Please Login to comment...