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 2086. Minimum Number of Food Buckets to Feed the Hamsters #177

Open
Woodyiiiiiii opened this issue Jan 13, 2023 · 0 comments
Open

Comments

@Woodyiiiiiii
Copy link
Owner

Woodyiiiiiii commented Jan 13, 2023

这道题带了点DPGreedy的思想。

类型是辐射型,即数组中元素会对周边元素产生影响。

这种类型的解决问题,是尽量辐射更多范围。所以在这里,因为大部分都是从左到右遍历的,故尽量把Bucket放在hamster的右边;如果放不了,再考虑是否能放左边;都放不了,则失败,返回-1。

class Solution {
    public int minimumBuckets(String hamsters) {
        int ans = 0;
        int n = hamsters.length();
        char[] chars = hamsters.toCharArray();
        for (int i = 0; i < n; ++i) {
            char c = chars[i];
            if (c == 'H') {
                if (i - 1 >= 0 && chars[i - 1] == 'B') {
                    continue;
                }
                if (i + 1 >= n || chars[i + 1] == 'H') {
                    if (i - 1 >= 0 && chars[i - 1] == '.') {
                        ans++;
                        chars[i - 1] = 'B';
                    } else {
                        return -1;
                    }
                } else {
                    chars[i + 1] = 'B';
                    ++ans;
                }
            }
        }
        return ans;
    }
}

类似题目:


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