768、最多能完成排序的块(贪心算法)

题目链接:https://leetcode-cn.com/problems/max-chunks-to-make-sorted-ii/description/

析:

看到这个问题,求最大值,是一个最优化的问题。先考虑暴力解法,感觉会很繁琐;再考虑动态规划,在列递归方程的时候也很繁琐;这时便考虑到“贪心算法”,从左到右,每次做出当前最优的选择,这里也不会落入局部最优解;

代码如下:

class Solution {
public:
    int maxChunksToSorted(vector<int>& arr) {
        int len = arr.size();
        int count = 1;
        
        int leftmax = arr[0];
        int *rightmin = new int[len];
        rightmin[len - 1] = arr[len - 1];
        
        for(int i = len - 2 ; i > 0 ; i --)
        {
            rightmin[i] = fmin(arr[i] , rightmin[i + 1]);
        }
        
        for(int i = 1 ; i < len ; i ++)
        {
            if(leftmax <= rightmin[i])
            {
                count ++;
                leftmax = arr[i];
            }
            else
            {
                leftmax = fmax(arr[i] , leftmax);
            }
        }
        
        return count;
    }
};

 

posted @ 2018-09-02 21:19  outthinker  阅读(528)  评论(0编辑  收藏  举报