How to find the maximum value we can achieve by picking k elements from an array in Pascal

2 Answers

0 votes
// Manual Sort (compatible with all Free Pascal versions)
 
program MaxKSum;

procedure QuickSort(var A: array of Integer; L, R: Integer);
var
  i, j, pivot, temp: Integer;
begin
  i := L;
  j := R;
  pivot := A[(L + R) div 2];
 
  repeat
    while A[i] > pivot do Inc(i);   // descending
    while A[j] < pivot do Dec(j);
 
    if i <= j then
    begin
      temp := A[i];
      A[i] := A[j];
      A[j] := temp;
      Inc(i);
      Dec(j);
    end;
  until i > j;
 
  if L < j then QuickSort(A, L, j);
  if i < R then QuickSort(A, i, R);
end;
 
function MaxSumK(var arr: array of Integer; k: Integer): Integer;
var
  i: Integer;
begin
  QuickSort(arr, Low(arr), High(arr));
 
  MaxSumK := 0;
  for i := 0 to k - 1 do
    MaxSumK := MaxSumK + arr[i];
end;
 
var
  arr: array of Integer;
begin
  arr := [11, 2, 4, 9, 3, 6, 5, 1];
  WriteLn('Maximum sum = ', MaxSumK(arr, 3));
end.
 
 
 
(*
run:
 
Maximum sum = 26
 
*)

 



answered Apr 5 by avibootz
edited Apr 5 by avibootz
0 votes
// Manual Sort (compatible with all Free Pascal versions)
 
program MaxKElements;

type
  TIntArray = array of Integer;
 
var
  nums: TIntArray;
  k, i, total: Integer;
 
procedure SortArray(var arr: TIntArray);
var
  i, j, temp: Integer;
begin
  for i := Low(arr) to High(arr) do
    for j := i + 1 to High(arr) do
      if arr[i] < arr[j] then { Sort Descending }
      begin
        temp := arr[i];
        arr[i] := arr[j];
        arr[j] := temp;
      end;
end;
 
begin
  nums := TIntArray.Create(11, 2, 4, 9, 3, 6, 5, 1);
  k := 3;
  total := 0;
 
  SortArray(nums);
 
  for i := 0 to k - 1 do
    total := total + nums[i];
 
  writeln('Maximum sum of ', k, ' elements: ', total);
end.
 
 
 
(*
run:
 
Maximum sum of 3 elements: 26
 
*)
 

 



answered Apr 5 by avibootz

Related questions

...