Maximum Value of subarray

Is there any function that returns the maximum number from a subarray of a longint array?

For example:

I have the array: [2,3,6,2,9,4,2,4]

I want the maximum value of the first 5 elements [2,3,6,2,9] of the array (9)

Which is the best solution?

Upvotes: 0

Views: 636

Answers (2)

Abstract type
Abstract type

Reputation: 1921

More concretly this is the easy solution: write a function which takes an array, the lowest and the highest indexes as parameter.

program Project1;

uses sysutils;

type TIntegerArray = array of Integer;

function maxInRange(const anArr: TIntegerArray; boundLow, boundHi: Integer): Integer;
var
  i: Integer;
begin
  result := anArr[boundLow];
  for i := boundLow + 1 to boundHi do
    if anArr[i] > result then
      result := anArr[i];
end;

const
  arr: array[0..7] of Integer = (2,3,6,2,9,4,2,4);

begin
  writeln(intToStr(maxInRange(arr,0,4)));
  readln;
end.

Upvotes: 0

NSimon
NSimon

Reputation: 5287

You don't need to create another array. The 1st solution that would come up is to loop inside your array, taking the first value as 'tempMaxValue', and then fetching your array comparing each value to the 'tempMaxValue'.

If the value is greater than 'tempMaxValue', update 'tempMaxValue' with that particular value and then jump to the next value in the array, otherwise just jump to the next value.

With this solution, you can manage the number of items you want to search into (here you wanted the greatest number within the 5 first elements, so your loop will go from 0 to 4)

Edit : (as @TLama said)

Upvotes: 5

Related Questions