top of page
Caută
  • Poza scriitoruluioanaunciuleanu

Count the ways to reach the n’th stair in JAVA

You receive as an input a number representing sections. Each section is composed of two plots, on either side of the road. You must find all possible ways to construct buildings in the plots, considering that there has to be a space between any two buildings.


​Input: int stairs = 4; int climbMax = 2; Output: 5 Explanation: The ways to climb 4 stairs , climbing maximum 2 stairs at a time are: (1, 1, 1, 1), (1, 1, 2), (2, 1, 1), (1, 2, 1), (2, 2).


Solution:


1. static int countWaysToClimbStairs(int stairs, int climbMax) { 2. int[] countingValues = new int[stairs + 1]; 3. int temporary = 0; 4. countingValues[0] = 1; 5. 6. for (int i = 1; i <= stairs; i++) { 7. int stair = i - climbMax - 1; 8. int previousElement = i - 1; 9. if (stair >= 0) { 10. temporary -= countingValues[stair]; 11. } 12. temporary += countingValues[previousElement]; 13. countingValues[i] = temporary; 14. } 15. return countingValues[stairs]; 16. } 17.

3 afișări0 comentarii

Postări recente

Afișează-le pe toate

Weighted Job Scheduling in JAVA

You receive a list of jobs that have three elements: start time, finish time and profit. You have to schedule the jobs with no overlapping, in order to obtain the maximum profit. Solution: 1. static

Tiling Problem in JAVA

You can use a board that is 2 x n size. The tiles are of size 2 x 1. Count the number of ways to tile the board. Tiles can be placed vertically 2 x 1 or horizontally as 1 x 2. Solution: 1. static

bottom of page