• 求子数组的最大和


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

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

    View Code
    public static void MaxSum(int[] arr) {
             
    int startSumMax = 0;
             
    int endSumMax = 0;    
             
    int startIndex = 0;
             
    int endIndex = 0;
             
    int max = 0;
            
    for (int i = 0; i < arr.length; i++) {
                
    int startTmp = SumInt(startSumMax, arr[i]);
                
    int endTmp = SumInt(endSumMax, arr[arr.length - 1 - i]);
                
    if (startTmp < arr[i]) {
                    startIndex 
    = i;
                    startSumMax 
    = arr[i];
                } 
    else {

                    startSumMax 
    = startSumMax + arr[i];
                }
                
    if (endTmp < arr[arr.length - 1 - i]) {
                    endIndex 
    = arr.length - 1 - i;
                    endSumMax 
    = arr[arr.length - 1 - i];
                } 
    else {
                    endSumMax 
    = endSumMax + arr[arr.length - 1 - i];
                }
            }
            
    if (startIndex > endIndex) {
                
    //Error
            }
            
    for (int i = startIndex; i < endIndex; i++) {
                max 
    = max + arr[i];
            }
        }
  • 相关阅读:
    FR5一二维码设置条码值
    is application failed to start because no Qt platform plugin could be initialized. Reinstalling the application may fix this problem
    sql server 2012插入排序后的数据到临时表无效
    Fr3设置图片打印
    created a ThreadLocal with key of type [oracle.jdbc.driver.AutoKeyInfo$1]
    jdbc oracle 连接串
    初玩PLSQL连接 Oracle
    java.lang.NumberFormatException: For input string: "F"
    网站被截持到赌博网
    java时间差
  • 原文地址:https://www.cnblogs.com/hda37210/p/2065586.html
Copyright © 2020-2023  润新知