Interview friendly solution and Java Impl
It took me a few looks to identify this is the same problem as max rect in histrogram.\n\nI know there is a famous stack-based solution for that and each time t
It took me a few looks to identify this is the same problem as max rect in histrogram.\n\nI know there is a famous stack-based solution for that and each time that took me a while to re-understand, and I\'m not 100% comfortable with that yet, thus I cannot say I can re-come up with the stack solution in interview and explain it clearly.\n\nHowever I came up below solution since years ago and applied it a few times. It\'s like parent finding for Union Find, but this is not Union Find. By the look it should have time complexity O(NlogN) but in reality it is always very fast and out-perform O(N) solutions. I got no mathematical proof why, but probably like fast sort, it\'s just fast in real life with simple data structures and linear operatons.\n\nThe idea is,\n**Consider every position as the min value of a subarray, what is the longest subarray we can form?**\n\n1. Find the nearest position to the left that is smaller than current position\n2. Find the nearest position to the right that is smaller than current position\n3. Get the subarray (inbetween above 2 positions) sum with presums\n4. Got a candidate, keep the max candidate\n\n```\nclass Solution {\n    public int maxSumMinProduct(int[] nums) {\n        int N = nums.length;\n        \n        // First smaller value to the left\n        int[] left = new int[N];\n        for (int i = 0; i < N; i++) {\n            int prev = i - 1;\n            while (prev >= 0 && nums[prev] >= nums[i]) prev = left[prev];\n            left[i] = prev;\n        }\n        \n        // First smaller value to the right\n        int[] right = new int[N];\n        for (int i = N - 1; i >= 0; i--) {\n            int next = i + 1;\n            while (next < N && nums[next] >= nums[i]) next = right[next];\n            right[i] = next;\n        }\n        \n        // PreSums\n        long[] sums = new long[N + 1];\n        for (int i = 0; i < N; i++) sums[i + 1] = sums[i] + nums[i];\n        \n        // Find min-prod\n        long ans = 0;\n        for (int i = 0; i < N; i++) {\n            int l = left[i];\n            int r = right[i];\n            long sum = sums[r] - sums[l + 1];\n            ans = Math.max(ans, sum * nums[i]);\n        }\n        return (int)(ans % 1_000_000_007);\n    }\n}\n```
[]