zoukankan      html  css  js  c++  java
  • 连续子数组的最大和-剑指Offer

    连续子数组的最大和

    题目描述

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

    思路

    1. 我们可以举例分析数组的规律,用一个变量来存储最大值,另一个变量存储当前的和,若当前和为负值,则后面加的和都会比当前的小,所以当为负值时把当前的和设置为0重新开始计算
    2. 我们也可以通过动态规划的方法来解决这个问题

    代码

    public class Solution {
        public int FindGreatestSumOfSubArray(int[] array) {
            if (array == null || array.length == 0) {
                return 0;
            }
            int curSum = 0;
            int sum = 0x80000000;
            for (int i = 0; i < array.length; i++) {
                if (curSum < 0) {
                    curSum = array[i];
                } else {
                    curSum += array[i];
                }
                if (curSum > sum) {
                    sum = curSum;
                }
    
            }
            return sum;
        }
    }
  • 相关阅读:
    复制域 动态域
    字段
    ik分词器
    redis配置文件
    注解事务头部
    springSecurity配置解析
    sprring安全的.xml
    springSecurity需要的webxml
    nginx负载均衡+keepalived高可用
    20190802_Nginx基础
  • 原文地址:https://www.cnblogs.com/rosending/p/5637863.html
Copyright © 2011-2022 走看看