189k views
2 votes
In JAVA 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. For example, with the heights {5, 3, 6, 7, 2} and start=2, end=4 yields a sum of 1 + 5 = 6. The start end end index will both be valid indexes into the array with start <= end.

sumHeights([5, 3, 6, 7, 2], 2, 4) → 6
sumHeights([5, 3, 6, 7, 2], 0, 1) → 2
sumHeights([5, 3, 6, 7, 2], 0, 4) → 11

User Rijk
by
4.5k points

1 Answer

6 votes

Answer:

// here is code in Java.

import java.util.*;

class Main

{

// method to calculate sum of height

public static int sumHeights(int[] h, int s, int e)

{

// variable to store sum

int sum_of_height = 0;

// calculate sum

for(int i = s; i < e; i++)

sum_of_height += Math.abs(h[i] - h[i+1]);

// return the sum

return sum_of_height;

}

// driver method

public static void main (String[] args) throws java.lang.Exception

{

// declare and initialize the array

int height[]={5, 3, 6, 7, 2};

// start index

int start=2;

// end index

int end=4;

// call the method and print the sum of height

System.out.println("Sum of height is:"+ sumHeights(height,start,end));

}

}

Step-by-step explanation:

Declare and initialize the array.initialize the "start" and "end" index.Call the method sumHeights() with array, start and end as parameter.In the sumHeights() method, create and initialize a variable "sum_of_height" with 0. Then find the absolute difference from start with its next element and add them to sum_of_height.Return the sum of height and print it in the main method.

Output:

Sum of height is:6

User Vcuankit
by
4.9k points