给定一个数组序列, 需要求选出一个区间, 使得该区间是所有区间中经过如下计算的值最大

Python 版本的解析请参见https://blog.csdn.net/weixin_42001089/article/details/84203651

此处本人给出java版本,其实java的栈很好用;


import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.Scanner;
import java.util.Stack;

//元素的相应位置不能变
public class Main_sum {

    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int[] num = new int[n + 1];

        for (int i = 0; i < n; i++) {
            num[i] = sc.nextInt();
        }
        num[n] = 0; // append 0 to the last position

        /*
        int n = 5;
        int[] num = new int[n + 1];
        Random rand = new Random();
        for (int i = 0; i < n; i++) {
            num[i] = rand.nextInt(100) + 1;
        }
         */
        Stack<Integer> stack = new Stack<Integer>();
        Stack<Integer> sumstack = new Stack<Integer>();
        int i = 0;
        int tempsum = 0;
        int result = 0;
        while (i < num.length) {
            if (stack.size() == 0 || num[i] > stack.lastElement()) {// 如果数组的元素大于栈顶  put it into the stack
                stack.add(num[i]);
                sumstack.add(tempsum); // accumlate add
                tempsum = 0;
                i++;

            } else { // small than top ele of stack; pop out, and cal the accumate result
                int temp = stack.pop(); // the top ele
                tempsum += (temp + sumstack.pop());  // accumate add
                result = Math.max(tempsum * temp, result); // if the max one, otherwise swap

            }

        }

        System.out.println(result);
    }

}

发布了242 篇原创文章 · 获赞 338 · 访问量 65万+

猜你喜欢

转载自blog.csdn.net/MrCharles/article/details/105212296