Beruflich Dokumente
Kultur Dokumente
(CS210A)
Lecture 4:
3 -5 3 8 2
-4 9 -6 3 -2 -8 3 -5 1
18
-2
7 -9
3 -5 3 8 2
-4 8 -6 3 -2 -8 3 -5 1
-4
-2
6
9
4
7
7 -9
S()=9
for = 5
Observation:
compute S() for each .
In order to solve the problem, it suffices to
..
5
time ?
S()
S()
()
S
?
S(
)
Any
relation
among
them ?
()
S
S()
S()
S() ?
S()
What is the
relation
between S()
and S() ?
7
Relation between
S() and S()
Subarray
corresponding to
S()
Subarray
corresponding
to S()
Theorem 1:
If S() > 0 then S() = S() + A[]
else S() = A[]
S[] A[];
O()
time
repetitions
for = 1 to
{
If S[] > 0 then S[] S[] + A[]
time
else S[] A[] O()
}
Scan S to return the maximum entry O()
time
}
Time complexity of the algorithm = O()
Homework:
Refine the algorithm so that it uses only O(1) extra space.
S[] A[]
for = 1 to
{
If S[] > 0 then S[] S[] + A[]
else S[] A[]
}
Scan S to return the maximum entry
}
What is the proof of
correctness of the algorithm ?
10
11
S[] A[]
for = 1 to
{
If S[] > 0 then S[] S[] + A[]
else S[] A[]
}
Scan S to return the maximum entry
}
Question:
What needs to be proved in order to establish the correctness of
this algorithm ?
Ponder over this question before coming to the next
12
class
NEW PROBLEM:
LOCAL MINIMA IN A GRID
13
Does a local
minima exist
always ?
31
5 33 10
99
14
31
5 33 10
99
15
This should convince you that designing algorithm does not require any
thing magical !
16
2. Principle of simplification:
If you find a problem difficult,
.Try to solve its simpler version, and then
.Try to extend this solution to the original (difficult) version.
17
A new approach
Repeat : if current entry is not local minima, explore the neighbor
storing smaller value.
j
18
A new approach
Explore()
{
Let c be any entry to start with;
While(c is not a local minima)
{
c a neighbor of c storing smaller value
}
return c;
}
A new approach
Explore()
{
Let c be any entry to start with;
While(c is not a local minima)
{
c a neighbor of c storing smaller value
}
return c;
}
First principle:
Do not discard
Explore()
Second principle:
Simplify the problem
20
21