Home > Software design >  How do I write a program which returns the index of the local maximum?
How do I write a program which returns the index of the local maximum?

Time:10-03

How do I write a program that takes a list of numbers, then finds the index of the local maxima

I have been trying to write the program but I am not sure how to approach it. The local maximum refers to an integer in the list which is larger than the two adjacent numbers next to it. Examples of what the program does;

CheckMaximum(data) 
data = {1,7,1,24,15}

data being an array of at least one integer

it would have an output of

[1, 3]

because the local maximums are 7 and 24, which are in the indexes of 1 and 3 respectively. If the array entered has only one number, it would return a [0]

CodePudding user response:

You can loop from index 1 to 2 less than the size of the list, comparing each element with the elements immediately before and after (add or subtract 1 from the current index).

static List<Integer> CheckMaximum(List<Integer> data) {
    if (data == null || data.size() < 2) return List.of(0); // this case is unclear
    List<Integer> res = new ArrayList<>();
    for (int i = 1; i < data.size() - 1; i  )
        if (data.get(i) > data.get(i - 1) && data.get(i) > data.get(i   1)) res.add(i);
    return res;
}

CodePudding user response:

here's a hint:

for (int i = 1; (i 1) < items.length; i  ){
    int current = items[i];
    int previous = items[i-1];
    int next = items[i 1];

    if ((current > previous) && (current > next)) {
         // i is a local maxima
    }
}
  • Related