knowing that arrays start with inded 0, index 2 points to the value 6why we are taking only index 2 and index 3 why not index 0,1 or index 3, 4 ?
index 3 is the value of 7
the difference in height is absolute( 6 - 7 ) which is +1
For example, with the heights {5, 3, 6, 7, 2} and start=2, end=4 yields a sum of 1 + 5 = 6.
means the walk starts at index 2, means value 6above is clear as index 2 is clearly 6 within given array
next stop is at value/altitute 7, so there is 1 (unit) walked UPabove not clear.
last stop is at value/altitude 2, so the is 5 (units) walked DOWNnot clear on above too. What is this thing about walk up and walk down. what is the refence point and what is the target point to find difference from target minus reference??
I did that using excel + reworked with ms paint the screenshot ...
you don't "need" a new graph to cross check...
just do it step by step ...
5 starting step (0)
3 diff: -2 => running sum: 2
6 diff: +3 => running sum : 5
7 diff: +1 => running sum: 6
2 diff: - 5 => runnng sum : 11 , last step (4), this is the result
5 starting step (0)
3 diff: -2 => running sum: 2
6 diff: +3 => running sum : 5
7 diff: +1 => running sum: 6
2 diff: - 5 => runnng sum : 11 , last step (4), this is the result
Are you familiar with the mathematical concept of absolute value?
https://www.mathsisfun.com/numbers/absolute-value.html
sorry, but that goes far beyond this question.let me open new question for that different discussion.
loop thorugh given array from startPsedo Code is as above
find the absolute difference with next element
continue till end by summing above differences
return sum
public int sumHeights(int[] heights, int start, int end) {
int diff=0;
int sum=0;
int absDiff=0;
for(int i=start; i<end; i++){
diff=heights[i+1]-heights[i];
absDiff=Math.abs(diff);
sum=sum+absDiff;
}
return sum;
}
above passed all tests. Any improvements or alternate approaches?
If you are experiencing a similar issue, please ask a related question
Title | # Comments | Views | Activity |
---|---|---|---|
Windows 10 IE Certificate Issue | 10 | 45 | |
How to get time difference in minutes and seconds only between 2 dates | 2 | 41 | |
Java: The Public Class Main | 4 | 16 | |
JAVA API design with micro service cloud in mind | 1 | 18 |
Join the community of 500,000 technology professionals and ask your questions.