gudii9
asked on
sumHeights2 challenge
Hi,
i am working one below challenge
http://codingbat.com/prob/p157900
i was not clear on below description
(A variation on the sumHeights problem.) We have an array of heights, representing the altitude along a walking trail. Given start/end indexes into the array, return the sum of the changes for a walk beginning at the start index and ending at the end index, however increases in height count double. For example, with the heights {5, 3, 6, 7, 2} and start=2, end=4 yields a sum of 1*2 + 5 = 7. The start end end index will both be valid indexes into the array with start <= end.
how below results are 7,2, 15 each? please advise
sumHeights2([5, 3, 6, 7, 2], 2, 4) → 7
sumHeights2([5, 3, 6, 7, 2], 0, 1) → 2
sumHeights2([5, 3, 6, 7, 2], 0, 4) → 15
i am working one below challenge
http://codingbat.com/prob/p157900
i was not clear on below description
(A variation on the sumHeights problem.) We have an array of heights, representing the altitude along a walking trail. Given start/end indexes into the array, return the sum of the changes for a walk beginning at the start index and ending at the end index, however increases in height count double. For example, with the heights {5, 3, 6, 7, 2} and start=2, end=4 yields a sum of 1*2 + 5 = 7. The start end end index will both be valid indexes into the array with start <= end.
how below results are 7,2, 15 each? please advise
sumHeights2([5, 3, 6, 7, 2], 2, 4) → 7
sumHeights2([5, 3, 6, 7, 2], 0, 1) → 2
sumHeights2([5, 3, 6, 7, 2], 0, 4) → 15
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ok, clarified on that other question
ASKER
public int sumHeights2(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];
if(diff<0){
absDiff=Math.abs(diff);
}else{
absDiff=2*diff;
}
sum=sum+absDiff;
}
return sum;
}
above passes all tests . Any improvements or alternate approaches?
looks correct to me.
as mentioned in the other question, you should consider commenting the code
as mentioned in the other question, you should consider commenting the code
Alternative method without absolute -
int diff=0;
int sum = 0;
for(int j=start; j<end; j++) {
diff = (heights[j + 1] > heights[j]) ? 2*(heights[j + 1] - heights[j]) : -(heights[j + 1] - heights[j]);
sum = sum + diff;
}
return sum;
int diff=0;
int sum = 0;
for(int j=start; j<end; j++) {
diff = (heights[j + 1] > heights[j]) ? 2*(heights[j + 1] - heights[j]) : -(heights[j + 1] - heights[j]);
sum = sum + diff;
}
return sum;
ASKER
: -(heights[j + 1] - heights[j])
i like this trick of multiplying with minus
ASKER