字节跳动 区间最大值 牛客网

简介: 字节跳动 区间最大值 牛客网

image.png


核心的思想是:栈+前缀和


public int getMax(int[] numbers){
    if(numbers.length==0||numbers==nul){
        return 0;
    }
    Stack<Integer> stack=new Stack<>();
    int max=0;
    //求前缀和的数组
    int[] sum=new int[numbers.length+1];
    for(int i=1;i<=numbers.length;i++){
        sum[i]=sum[i-1]+numbers[i-1];
    }
    for(int i=0;i<numbers.length;i++){
        while(!stack.isEmpty()&&numbers[i]<numbers[stack.peek()]){
            int index=stack.pop();
            int left=i;
            int right=i;
            if(stack.isEmpty()){
                left=0;
            }else{
                left=index;
            }
            max=Math.max(max,numbers[index]*(sum[right]-sum[left]));
        }
        stack.push(i);
    }
    while(!stack.isEmpty()){
        int index=stack.pop();
        int left=numbers.length;
        int right=numbers.length;
        if(stack.isEmpty()){
            left=0;
        }else{
            left=index;
        }
        max=Math.max(max,numbers[index]*(sun[right]-sum[left]));
    }
    return max;
}
目录
相关文章
|
6月前
【Leetcode -506.相对名次 -507.完美数】
【Leetcode -506.相对名次 -507.完美数】
26 0
【剑指offer】-和为S的两个数-38/67
【剑指offer】-和为S的两个数-38/67
|
4月前
牛客网-旋转数组的最小数字
牛客网-旋转数组的最小数字
16 0
|
4月前
蓝桥杯 1的个数
蓝桥杯 1的个数
21 0
|
5月前
|
算法
代码随想录算法训练营第二天 | LeetCode 977.有序数组的平方、209.长度最小的子数组、59. 螺旋矩阵 II
代码随想录算法训练营第二天 | LeetCode 977.有序数组的平方、209.长度最小的子数组、59. 螺旋矩阵 II
39 0
|
5月前
|
算法 索引
代码随想录算法训练营第二天 |977.有序数组平方,209.长度最小的字数组,59.螺旋矩阵
代码随想录算法训练营第二天 |977.有序数组平方,209.长度最小的字数组,59.螺旋矩阵
|
5月前
|
算法 索引
代码随想录训练营Day2:1.有序数组的平方 2.长度最小的子数组3,螺旋矩阵
代码随想录训练营Day2:1.有序数组的平方 2.长度最小的子数组3,螺旋矩阵
13 0
|
8月前
|
算法 索引
代码随想录算法训练营第二天| 977.有序数组的平方 ,209.长度最小的子数组 ,59.螺旋矩阵II ,总结
代码随想录算法训练营第二天| 977.有序数组的平方 ,209.长度最小的子数组 ,59.螺旋矩阵II ,总结
|
9月前
【牛客面试必刷TOP101】有效括号序列、滑动窗口的最大值
【牛客面试必刷TOP101】有效括号序列、滑动窗口的最大值
|
10月前
剑指Offer - 面试题11:旋转数组的最小数字
剑指Offer - 面试题11:旋转数组的最小数字
46 0