前缀和数组等相关类型应该是long,溢出了,所以之前逻辑没问题但是却一直不对
一个数组的 最小乘积 定义为这个数组中 最小值 乘以 数组的 和 。
比方说,数组 [3,2,5] (最小值是 2)的最小乘积为 2 * (3+2+5) = 2 * 10 = 20 。
给你一个正整数数组 nums ,请你返回 nums 任意 非空子数组 的最小乘积 的 最大值 。由于答案可能很大,请你返回答案对 109 + 7 取余 的结果。
请注意,最小乘积的最大值考虑的是取余操作 之前 的结果。题目保证最小乘积的最大值在 不取余 的情况下可以用 64 位有符号整数 保存。
子数组 定义为一个数组的 连续 部分。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/maximum-subarray-min-product
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
import java.util.*;
class Solution {
public int maxSumMinProduct(int[] nums) {
if(nums == null || nums.length == 0){
return 0;
}
int len = nums.length;
long[] sums = new long[len];
sums[0] = nums[0];
// 前缀和数组
for(int i = 1;i < len;i++){
sums[i] = sums[i - 1] + nums[i];
// System.out.println(i + " " + sums[i]);
}
// 数组nums每个位置 左右最近的最小值位置
int[][] LeftRight = new int[len][2];
// // 用list保存数组下标
// ArrayList<Integer> list = new ArrayList<>();
// 单调栈 从栈底到栈顶 由小到大
Stack<List<Integer>> stack = new Stack<>();
// 记录乘积最大值
long res = 0;
// 遍历数组生成记录
for(int i =0;i < len;i++){
// 栈非空 且 从小到大的单调性被破坏 旧数 > 新数 先出栈 生成记录 后进栈
while(!stack.isEmpty() && nums[stack.peek().get(0)] > nums[i]){
// 用list保存数组下标
List<Integer> list = new ArrayList<>();
list = stack.pop();
// 生成记录
for(Integer j : list){
LeftRight[j.intValue()][0] = !stack.isEmpty() ? stack.peek().get(stack.peek().size() - 1).intValue() : 0; // 左边最近的最小值
LeftRight[j.intValue()][1] = i; // 右边最近的最小值
long sum = !stack.isEmpty() ? (sums[LeftRight[j.intValue()][1] - 1] - sums[LeftRight[j.intValue()][0]]) : sums[LeftRight[j.intValue()][1] - 1];
res = res >= sum * nums[j.intValue()] ? res : sum * nums[j.intValue()];
}
}
// 栈非空 且 旧数 等于 新数
if(!stack.isEmpty() && nums[stack.peek().get(0)] == nums[i]){
stack.peek().add(Integer.valueOf(i));
}
else{ // 栈空 直接进
// 用list保存数组下标
List<Integer> list = new ArrayList<>();
list.add(Integer.valueOf(i));
stack.push(list);
}
}
while(!stack.isEmpty()){
// 用list保存数组下标
List<Integer> list = new ArrayList<>();
list = stack.pop();
// 生成记录
for(Integer j : list){
LeftRight[j.intValue()][0] = !stack.isEmpty() ? stack.peek().get(stack.peek().size() - 1).intValue() : 0; // 左边最近的最小值
LeftRight[j.intValue()][1] = len - 1; // 右边最近的最小值
long sum = !stack.isEmpty() ? (sums[LeftRight[j.intValue()][1]] - sums[LeftRight[j.intValue()][0]]) : sums[LeftRight[j.intValue()][1]];
res = res >= sum * nums[j.intValue()] ? res : sum * nums[j.intValue()];
}
}
res = res % ((int)Math.pow(10,9) + 7);
return (int)res;
}
}
问题:怎么能减少执行时间呢?