Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Leetcode 2271. Maximum White Tiles Covered by a Carpet #119

Open
Woodyiiiiiii opened this issue May 15, 2022 · 0 comments
Open

Leetcode 2271. Maximum White Tiles Covered by a Carpet #119

Woodyiiiiiii opened this issue May 15, 2022 · 0 comments

Comments

@Woodyiiiiiii
Copy link
Owner

这道题是双周赛第三题。

看完题目,要知道关键的两点:

  1. 为了尽量满足cover更多的white tiles,carpet要从每个区间的左起点开始往右cover,而不用考虑从区间的右节点往左cover
  2. 为了时间复杂度,而且还是一个区间在另一个区间移动的问题,使用**sliding window(滑动窗口)**方法。

我做的时候两点都没想明白

class Solution {
    public int maximumWhiteTiles(int[][] tiles, int carpetLen) {
        
        long res = 0;
        // sort
        Arrays.sort(tiles, Comparator.comparingInt(a -> a[0]));

        long sq = 0;
        int l = 0;
        int r = 0;
        int n = tiles.length;
        while (r < n && l < n) {
            if (tiles[l][0] + carpetLen - 1 > tiles[r][1]) {
                sq += (tiles[r][1] - tiles[r][0] + 1);
                res = Math.max(res, sq);
                ++r;
            } else {
                if (tiles[l][0] + carpetLen - 1 >= tiles[r][0]) {
                    res = Math.max(res, sq + (tiles[l][0] + carpetLen - tiles[r][0]));
                }
                if (tiles[l][0] + carpetLen - 1 > tiles[l][1]) {
                    sq -= (tiles[l][1] - tiles[l][0] + 1);
                } else {
                    sq -= (carpetLen);
                }
                ++l;
                r = Math.max(r, l);
            }
        }

        return (int)res;
        
    }
}

参考资料:

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant