开发者

Find the Number of "Big Steps" along a walking Trail

开发者 https://www.devze.com 2023-03-04 03:41 出处:网络
We have an array of heights, representing the altitude along a walking trail. Given start/end i开发者_Python百科ndexes into the array, return the number of \"big\" steps for a walk starting at the sta

We have an array of heights, representing the altitude along a walking trail. Given start/end i开发者_Python百科ndexes into the array, return the number of "big" steps for a walk starting at the start index and ending at the end index. We'll say that step is big if it is 5 or more up or down. The start and end index will both be valid indexes into the array with start <= end.

bigHeights({5, 3, 6, 7, 2}, 2, 4) → 1      
bigHeights({5, 3, 6, 7, 2}, 0, 1) → 0     
bigHeights({5, 3, 6, 7, 2}, 0, 4) → 1     

Im stuck with this problem and unable to proceed further The function signature is as below::

public int bigHeights(int[] heights, int start, int end){ }


You just have to go through the heights array, compute the absolute value of differences, and count:

public int bigHeights(int[] heights, int start, int end){ 
    int bigsteps = 0;
    for (int i = start + 1; i <= end; i++) {
        if (Math.abs(heights[i] - heights[i - 1]) >= 5)
            bigsteps++;
    }
    return bigsteps;
}


The strategy you need is fairly simple: you only need to check each adjacent pair of numbers and count the number of "big" steps.

So what you'll need to do is:

  • Initialise a counter to zero
  • Loop from the start index to one less than the end index
  • Compare at each step heights[i] with heights[i+1] and if the difference is five or more increment the counter
  • Return the final value of the counter

Hopefully that gives you enough of a hint to solve the problem....

0

精彩评论

暂无评论...
验证码 换一张
取 消