一个整形数组,数组里有正数也有负数。 数组中连续的一个或多个整数组成一个子数组,每个子数组都有一个和,求所有子数组的和的最大值,要求时间复杂度为O(n)。...

本文介绍了一种求解最大子数组和的算法,通过遍历数组并排除小于0的子数组来实现,确保时间复杂度为O(n)。示例代码采用Java语言实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一个整形数组,数组里有正数也有负数。
数组中连续的一个或多个整数组成一个子数组,每个子数组都有一个和,求所有子数组的和的最大值,要求时间复杂度为O(n)。

例如输入的数组为1, -2, 3, 10, -4, 7, 2, -5,那么最大的子数组为3, 10, -4, 7, 2,因此输出为该子数组的和18

由于本人C\C++水平有限,所以使用java语言实现。

思路:从数组的后面排除小于0或者累加小于0的,用max记录被排除的子数组的和的最大值。

/***
 * @author lingxiasandu
 */
public class Test {

    public static void main(String[] args) {
        
        int[] a = {1, -2, 3, 10, -4, 7, 2, -5};
        int max = MaxSum(a);
        System.out.println(max);
    }
    
    /***
     * @param a 源数组
     * @return 返回子数组和的最大值
     */
    public static int MaxSum(int[] a){
        int sum = 0;
        int max = 0;
        for(int i=0;i<a.length;i++){
            sum = sum + a[a.length-i-1];
            if(a[a.length-i-1] >= 0){
               if(max < sum){
                  max = sum ;
                }
            }
            if(sum < 0){
                 sum = 0;
             }
        }
        return max;
    }

}

 

 

转载于:https://www.cnblogs.com/lingxiasandu/archive/2013/04/09/3009824.html

这个问题可以通过动态规划来解决。我们可以维护两个变量:`maxProduct` `currentMax`。`maxProduct` 存储的是当前找到的最大子数组乘积,而 `currentMax` 则存储当前连续正数的最大乘积,一旦遇到负数,就需要更新 `currentMax` 为 1,因为负数乘以负数仍然是正数,我们希望能尽可能地延长连续正数序列。 以下是Java代码实现: ```java import java.util.Stack; public class MaxSubArrayProduct { public static int getMaxSubarrayProduct(int[] nums) { if (nums == null || nums.length == 0) { return 0; } int maxProduct = nums[0]; int currentMax = nums[0]; boolean isNegative = false; // 标记是否遇到过负数 Stack<Integer> negations = new Stack<>(); // 负数标记栈 for (int num : nums) { if (num < 0) { if (!isNegative) { // 当前遇到第一个负数,记录当前位置并清空连续正数序列 isNegative = true; negations.push(-1); } else { // 后续的负数,更新currentMax为1 currentMax = 1; negations.push(-1); } } else { // 遇到正数,如果栈顶元素也是正数,则合并;否则结束连续正数序列,计算乘积 if (negations.peek() > 0) { currentMax *= negations.pop(); } currentMax *= num; // 如果栈为空栈顶元素是负数,更新maxProduct if (negations.isEmpty() || negations.peek() < 0) { maxProduct = Math.max(maxProduct, currentMax); } } } return maxProduct; } public static void main(String[] args) { int[] nums = {1, -2, 3, 4}; System.out.println(getMaxSubarrayProduct(nums)); // 输出12 } } ``` 在这个代码中,我们会遍历整个数组,遇到负数时处理连续负数序列,遇到正数时结合之前的正数单独的正数计算当前子数组的最大乘积。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值