Suppose an array of integers is given:

{1,3,2,4,6,5,2} 
- MAX: 6

Using Brute force, finding maximum element in this is to observe every element (each element is a candidate for the solution), thus searching entire search space.

Considering Greedy approach, we will modify the maximum element at each element of the array if necessary. Thus a local optimal choice will eventually lead to global optimal choice.

Are brute force and greedy approach similar here? So what exacty the difference between two algos in general?

Approach:

Brute force - Starting from first element - 1 taking it as max. Now considering each and every next element in array - entire search space. Choosing maximum at each step if necessary. This is brute force.

Greedy Algorithm - starting from nothing, taking first element - taking it max as 1. Then considering second element - 3, making local optimal choice between 1 and 3- taking 3 as maximum. And so on for other elements. At last, we will have 6 as maximum element- the global optimal choice.

How will you exactly tell the difference between the two algos in general?

2

There are 2 answers

2
Nikhil Saldanha On

Finding the maximum element in an unsorted array will require the brute-force approach.

There are ways of minimizing the complexity of this operation by using data-structures such as heaps, which sort the data as it is being added to the structure.

3
James On

A greedy algorithm might look something like this:

pick random starting point
if any of the two neighbors have higher value:
    move to the neighbor
else:  
    return value at current point

I would not call the linear scan of an array a greedy algorithm.