907. 子数组的最小值之和

public class Solution {
    public int sumSubarrayMins(int[] A) {
        int n = A.length;
        long ans = 0;
        final long MOD = (long) 1e9 + 7;
        for (int i = 0; i < n; i++) {
            int min = Integer.MAX_VALUE;
            int r = 0, l = 0;
            for (int j = i - 1; j >= 0; j--) {
                if (A[j] >= A[i]) {
                //注意,左右两次判断长时必须有且只有一个是小于等于,这样可以包含全部情况,比如样例[71,55,82,55]
                    l++;
                } else
                    break;
            }
            for (int j = i + 1; j < n; j++) {
                if (A[j] > A[i]) {
                    r++;
                } else
                    break;
            }
            long temp = A[i] * (r + 1) * (1 + l);
//            System.out.println(temp);
            temp %= MOD;
            ans += temp;
            ans %= MOD;
        }
        ans %= MOD;
        return (int) ans;
    }

    public static void main(String[] args) {
        Solution solution = new Solution();
        int[] a = {85};
        int ans = solution.sumSubarrayMins(a);
        System.out.println(ans);
        System.out.println((long)Math.pow(10, 9) + 7);
    }

}

leetcode上使用栈的方法,感觉没有上面的简洁,也是左右方向拓展,求组合的总数,也是必须有一边是 =

猜你喜欢

转载自blog.csdn.net/qq_25987491/article/details/82818653