贪婪算法中的局部最大值与全局最大值

时间:2016-03-26 23:15:20

标签: algorithm

在我们的算法类中,教授说如果在实现贪婪算法时我们陷入局部最大值并因此假设不可能再进行改进,则可能导致实现失败。有人可以举例说明何时会发生这种情况?

1 个答案:

答案 0 :(得分:1)

想象一下你需要在数组中找到最大数字,它具有内聚值(类似于横向,近场之间的差异不能高于1)。您不希望为了性能原因检查所有值,您可以尝试一个简单的贪婪算法,例如:检查近似值,如果它更高,则朝这个方向走,如果它的下方走向另一个方向:

public static void findHighestValue(int[] landscape){
    boolean leftChecked = false;
    boolean rightChecked = false;
    // we start in the middle of that array
    int currentIndex = landscape.length / 2;
    // do work until both directions are checked
    while(!leftChecked || !rightChecked){
        //check left boundary
        if(currentIndex == 0)
            leftChecked = true;
        //check right bound
        if(currentIndex == landscape.length - 1)
            rightChecked = true;
        //first check if left value is equal or higher then current value
        if(!leftChecked){
            if(landscape[currentIndex - 1] >= landscape[currentIndex]){
                currentIndex--;
            } else {
                leftChecked = true;
            }
        } else if(!rightChecked) {
            //same for right side
            if(landscape[currentIndex + 1] >= landscape[currentIndex]){
                currentIndex++;
            } else {
                leftChecked = true;
            }
        }
    }
    //print the result
    System.out.println("local maximum at index: " + currentIndex);
}

现在尝试使用以下值来调用该方法:{1,1,2,3,4,5,4,4,3,2,3,4,5,6,7,6,5}。根据算法的起点,它将找到5作为局部最大值或7作为全局最大值

正如您所看到的,此算法将转到本地maxmum并且无法离开

相关问题