LeetCode 768. Max Chunks To Make Sorted II (思维)

You are given an integer array arr.

We split arr into some number of chunks (i.e., partitions), and individually sort each chunk. After concatenating them, the result should equal the sorted array.

Return the largest number of chunks we can make to sort the array.

Example 1:

Input: arr = [5,4,3,2,1]
Output: 1
Explanation:
Splitting into two or more chunks will not return the required result.
For example, splitting into [5, 4], [3, 2, 1] will result in [4, 5, 1, 2, 3], which isn't sorted.

Example 2:

Input: arr = [2,1,3,4,4]
Output: 4
Explanation:
We can split into two chunks, such as [2, 1], [3, 4, 4].
However, splitting into [2, 1], [3], [4], [4] is the highest number of chunks possible.

Constraints:

  • 1 <= arr.length <= 2000
  • 0 <= arr[i] <= 108

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

题目大意:给一个数组,求最多可以分成多少块,使得每块排完序后拼起来是单调递增的

题目分析:我的做法是对每个点找到距离其右边最远的小于它的位置,然后判断当前点是否为某一段的终点,且该终点为当前向右延伸的最远点,如果是则可以在此处进行一次切分

时间复杂度是n^2的,比较挫

11ms,时间击败7%

class Solution {
    public int maxChunksToSorted(int[] arr) {
        int n = arr.length;
        int ed[] = new int[n];
        for (int i = 0; i < n; i++) {
            int j = n - 1;
            while (j > i && arr[j] >= arr[i]) {
                j--;
            }
            ed[i] = j;
        }
        int ans = 0, ma = 0;
        for (int i = 0; i < n; i++) {
            ma = Math.max(ed[i], ma);
            if (ed[i] == i && ed[i] == ma) {
                ans++;
            }
        }
        return ans;
    }
}

比较好的做法是维护从左往右的最大值和从右往左的最小值,如果leftMax[i] <= rightMin[i + 1],则显然左侧可以被切成一段

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值