The O(N
3
) Algorithm (brute force method - exhaustive search – see example)
General Observation Analysis
Look at the three loops:
The
i
loop executes
SIZE
(or N) times.
The
j
loop executes
SIZE-1
(or N-1)
times.
The
k
loop executes
SIZE-1
times in the worst case (when i = 0).
This
gives a rough estimate that the algorithm is O(N
3
).
Precise Analysis Using Big-Oh Notation
In all cases the number of times that, sum += a[k], is executed is equal to the
number of ordered triplets (i, j, k) where 1
≤
i
≤
k
≤
j
≤
N
2
(since
i
runs over
the whole index,
j
runs from
i
to the end, and
k
runs from
i
to
j
).
Therefore,
since
i
,
j
,
k
, can each only assume 1 of n values, we know that the number of
triplets must be less than n(n)(n) = N
3
but
i
≤
k
≤
j
restricts this even further.
By combinatorics it can be proven that the number of ordered triplets is n(n+1)
(n+2)/6.
Therefore, the algorithm is O(N
3
).
Day 4 -
2
Combinatorics Example
Suppose we have four values: 1, 2, 3, and 4.
Then the number of triplets
that can be form where 1
≤
i
≤
k
≤
j
≤
N is (N(N+1)(N+2))/6 = 120/6 =
20.
They are: (1,1,1) (1,1,2) (1,1,3) (1,1,4) (1,2,2) (1,3,3) (1,4,4) (1,2,3)
(1,2,4)
(1,3,4) (2,2,2) (2,2,3) (2,2,4) (2,3,3) (2,3,4) (2,4,4) (3,3,3) (3,3,4) (3,4,4)
Algorithm
int MCSS = 0, sum = 0, start = 0, end = 0;
for (i = 0; i < SIZE; i++)
{for (j = 0; j < SIZE; j++)
{
sum = 0;
for (k = i; k <= j; k++)
sum += a[k];
if (sum > MCSS)
{
MCSS = sum;
start = i;
end = j;
}
}
}
return MCSS;