1

My program takes a pair of numbers and subtracts them from one another then adds all the differences from the pairs back up for a total.

My problem is that some of the numbers overlap, by numbers I am using start and end times. I need to find a way to disregard overlapping numbers so that an input of

{{10, 14}, {4, 18}, {19, 20}, {19, 20}, {13, 20}

returns a total of 16 and not 27. Thus far I have created another array called hours to check off times already existing. Here is that portion of code:

public static int monitoring(int[][] intervals) {
    int sum = 0;
    int start = 0;
    int end = 0;
    boolean[] hours = new boolean[24];
    int count = 0;

    for(int i = 0; i < intervals.length; i++) {
        end = intervals[i][1];
        start = intervals[i][0];    
        for(int j = start; j < end; j++) {
            hours[j] = true;
            count++;
        sum += end - start;
        }
    }

    return sum;
Rick Smith
  • 9,031
  • 15
  • 81
  • 85
Robert
  • 97
  • 1
  • 4
  • 18

1 Answers1

2

I do not know what you are reaaly trying to get, 2 options possible:

  1. you are probably trying to get difference between maximum of the 2nd element if pairs, and minimum of the 1st element in pairs
  2. you want to count numbers of unique "points" (or hours) in given interval list.

Simplest solution can be:

            if (!hours[j]) {
                hours[j] = true;
                count++;
            }

In this case you do not even need "sum" variable.

Dae
  • 67
  • 4
  • I suggest a revision in your answer. Think of the case `{{4,8},{14,16}}`. I believe the OP wants the result to be 6, which is not `16-4`. Your code will give the correct result, but your text is a bit misleading. – RealSkeptic Mar 13 '15 at 18:25
  • Thank you all for your suggestions. I found adding another for loop such as: for(int x = 0; x < hours.length; x++){ if(hours[x]){ sum++; } } takes care of the problem. – Robert Mar 13 '15 at 20:58