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 1186. Maximum Subarray Sum with One Deletion #272

Open
Woodyiiiiiii opened this issue Jun 26, 2023 · 0 comments
Open

Leetcode 1186. Maximum Subarray Sum with One Deletion #272

Woodyiiiiiii opened this issue Jun 26, 2023 · 0 comments

Comments

@Woodyiiiiiii
Copy link
Owner

1186. Maximum Subarray Sum with One Deletion

1186. Maximum Subarray Sum with One Deletion

我的思路:这道题我一开始想着用滑动窗口,但发现很难解决选哪个删除的问题,又想用动态规划,结果发现动态规划做不到(无法分成子问题),最后转回滑动窗口,用treemap来找最小删除元素,结果发现左移情况无法确认。在这过程中花费了大量时间,我的思路错了。

正解是穷尽+kadane算法。

所以得到的教训是:

  1. 思路很重要,一定要确认好思路,不然会花费大量时间
  2. 要知道滑动窗口的关键——如何定义双指针的移动
  3. 脑子要转快点,思路不对一定要转换思维
class Solution {
    public int maximumSum(int[] arr) {
        int n = arr.length;
        int[] prefixDP = new int[n], suffixDP = new int[n];
        // kadane's algorithm
        int ans = arr[0];
        prefixDP[0] = arr[0];
        for (int i = 1; i < n; i ++) {
            prefixDP[i] = Math.max(prefixDP[i - 1] + arr[i], arr[i]);
            ans = Math.max(ans, prefixDP[i]);
        }
        suffixDP[n - 1] = arr[n - 1];
        for (int i = n - 2; i >= 0; i --) {
            suffixDP[i] = Math.max(suffixDP[i + 1] + arr[i], arr[i]);
            ans = Math.max(ans, suffixDP[i]);
        }
        // delete one element
        for (int i = 0; i < n; i++) {
            if (i == 0 && n > 1) {
                ans = Math.max(ans, suffixDP[i + 1]);
            } else if (i == n - 1 && n > 1) {
                ans = Math.max(ans, prefixDP[i - 1]);
            } else {
                if (i > 0 && i < n - 1) {
                    ans = Math.max(ans, prefixDP[i - 1] + suffixDP[i + 1]);
                }
            }
        }
        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