How to find the maximum sum of a subarray in Pascal

1 Answer

0 votes
program MaxSubArray;

const
  size = 11;
  // 4 + -1 + -1 + 2 + 3 = 7
  arr: array[1..size] of integer = (1, -2, 2, -3, 4, -1, -1, 2, 3, -5, 4);

function MaxSubArray: integer;
var
  i, currentSum, maxSum: integer;
begin
  maxSum := -MaxInt;  // INT_MIN 
  currentSum := 0;

  for i := 1 to size do
  begin
    if arr[i] > currentSum + arr[i] then
      currentSum := arr[i]
    else
      currentSum := currentSum + arr[i];

    if currentSum > maxSum then
      maxSum := currentSum;
  end;

  MaxSubArray := maxSum;
end;

begin
  writeln(MaxSubArray);
end.



(*
run:

7

*)

 



answered Sep 20, 2025 by avibootz
...