@@ -67,7 +67,8 @@ public static void main(String[] args) {
6767// 本题可以在leetcode上找到原题
6868// 测试链接 : https://leetcode.com/problems/maximum-subarray-min-product/
6969// 注意测试题目数量大,要取模,但是思路和课上讲的是完全一样的
70- // 注意溢出的处理即可
70+ // 注意溢出的处理即可,也就是用long类型来表示累加和
71+ // 还有优化就是,你可以用自己手写的数组栈,来替代系统实现的栈,也会快很多
7172public static int maxSumMinProduct (int [] arr ) {
7273int size = arr .length ;
7374long [] sums = new long [size ];
@@ -76,17 +77,20 @@ public static int maxSumMinProduct(int[] arr) {
7677sums [i ] = sums [i - 1 ] + arr [i ];
7778}
7879long max = Long .MIN_VALUE ;
79- Stack <Integer > stack = new Stack <Integer >();
80+ int [] stack = new int [size ];
81+ int stackSize = 0 ;
8082for (int i = 0 ; i < size ; i ++) {
81- while (!stack .isEmpty () && arr [stack .peek ()] >= arr [i ]) {
82- int j = stack .pop ();
83- max = Math .max (max , (stack .isEmpty () ? sums [i - 1 ] : (sums [i - 1 ] - sums [stack .peek ()])) * arr [j ]);
83+ while (stackSize != 0 && arr [stack [stackSize - 1 ]] >= arr [i ]) {
84+ int j = stack [--stackSize ];
85+ max = Math .max (max ,
86+ (stackSize == 0 ? sums [i - 1 ] : (sums [i - 1 ] - sums [stack [stackSize - 1 ]])) * arr [j ]);
8487}
85- stack . push ( i ) ;
88+ stack [ stackSize ++] = i ;
8689}
87- while (!stack .isEmpty ()) {
88- int j = stack .pop ();
89- max = Math .max (max , (stack .isEmpty () ? sums [size - 1 ] : (sums [size - 1 ] - sums [stack .peek ()])) * arr [j ]);
90+ while (stackSize != 0 ) {
91+ int j = stack [--stackSize ];
92+ max = Math .max (max ,
93+ (stackSize == 0 ? sums [size - 1 ] : (sums [size - 1 ] - sums [stack [stackSize - 1 ]])) * arr [j ]);
9094}
9195return (int ) (max % 1000000007 );
9296}
0 commit comments