Java > AP-1 > sumHeights2 (CodingBat Solution)

Problem:

(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.

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


Solution:

public int sumHeights2(int[] heights, int start, int end) {
    int tmp = 0;
  for (int i = start; i <= end-1; i++) {
    if (heights[i] < heights[i+1]) {
      tmp += 2 * (Math.abs(heights[i] - heights[i+1]));
    }
    else
      tmp += Math.abs(heights[i] - heights[i+1]);
  }
  return tmp;
}


3 comments :

  1. public int sumHeights2(int[] heights, int start, int end) {
    int sum = 0;
    int diff = 0;
    for (int i = start; i < end; i++) {
    if (i + 1 <= end) {
    if (heights[i] > heights[i + 1]) {
    diff = Math.abs(heights[i] - heights[i + 1]);
    sum += diff;
    }
    else{
    diff = 2*( Math.abs(heights[i] - heights[i + 1]));
    sum+=diff;
    }
    }
    }
    return sum;
    }

    ReplyDelete
  2. public int sumHeights2(int[] heights, int start, int end) {
    int sumHeight = 0;
    for(int i = start; i < end; i++)
    {
    sumHeight += (heights[i] < heights[i+1]) ? 2*(heights[i+1] - heights[i]) : heights[i] - heights[i+1];
    }
    return sumHeight;
    }
    Ternary is useful

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

    ReplyDelete

Follow Me

If you like our content, feel free to follow me to stay updated.

Subscribe

Enter your email address:

We hate spam as much as you do.

Upload Material

Got an exam, project, tutorial video, exercise, solutions, unsolved problem, question, solution manual? We are open to any coding material. Why not upload?

Upload

Copyright © 2012 - 2014 Java Problems  --  About  --  Attribution  --  Privacy Policy  --  Terms of Use  --  Contact