-
Notifications
You must be signed in to change notification settings - Fork 0
/
correct1.fl
110 lines (88 loc) · 2.51 KB
/
correct1.fl
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
// This is a correct Divide and Conquer based program for maximum subarray sum problem in fl!
// Algorithm based on https://www.geeksforgeeks.org/divide-and-conquer-maximum-sum-subarray/
program MaximumSubarraySum;
// Max array size
@defmacro N 1000
var
n, max_sum, i : integer;
arr: array [N] of integer;
// A utility funtion to find maximum of two integers
function max2(a, b:integer): integer;
begin
if a > b then
result := a
else
result := b;
return
end;
// A utility funtion to find maximum of three integers
function max(a, b, c:integer): integer;
begin
result := max2(max2(a,b), c);
return
end;
// Find the maximum possible sum in arr[] such that arr[m] is part of it
function maxCrossingSum(arr: array [N] of integer; l, m, h: integer): integer;
var
sum, left_sum, right_sum, i: integer;
begin
// Include elements on left of mid.
sum := 0;
left_sum := -32767; // This is the minimum integer allowed
for i := m downto l do
begin
sum := sum + arr[i];
if sum > left_sum then
left_sum := sum
end;
// Include elements on right of mid
sum := 0;
right_sum := -32767; // This is the minimum integer allowed
for i := m+1 to h do
begin
sum := sum + arr[i];
if sum > right_sum then
right_sum := sum
end;
// Return sum of elements on left and right of mid
result := left_sum + right_sum;
return
end;
// Returns maximum sum of subarray arr[l..h]
function maxSubArraySum(arr: array [N] of integer; l, h: integer): integer;
var
m : integer;
begin
// Base Case: Only one element
if l = h then
begin
result := arr[l];
return
end;
// Find middle point
m := (l+h)/2;
(* Return maximum of following three possible cases
a) Maximum subarray sum in left half
b) Maximum subarray sum in right half
c) Maximum subarray sum such that the subarray crosses the midpoint *)
result := max(maxSubArraySum(arr, l, m), maxSubArraySum(arr, m+1, h), maxCrossingSum(arr, l, m, h));
return
end;
// Main
begin
writeString("\nThis is a correct Divide and Conquer based program for maximum subarray sum problem in fl!\n\n");
writeString("Give me the size of your array: ");
n := readInteger();
writeString("\n");
for i := 0 to n-1 do
begin
writeString("Give me value ");
writeInteger(i+1);
writeString(": ");
arr[i] := readInteger()
end;
max_sum := maxSubArraySum(arr, 0, n-1);
writeString("\nMaximum contiguous sum is: ");
writeInteger(max_sum);
writeString("\n")
end.