📜  打印最大子阵列总和

📅  最后修改于: 2021-09-17 07:05:40             🧑  作者: Mango

给定一个数组arr[] ,任务是找到具有最大和的连续数字子数组的元素。

例子:

朴素的方法:朴素的方法是生成所有可能的子数组并打印具有最大和的子数组。
时间复杂度: O(N 2 )
辅助空间: O(1)

高效的方法:思想是使用Kadane’s Algorithm找到最大子数组和并存储具有最大和的子数组的开始和结束索引,并从开始索引到结束索引打印子数组。以下是步骤:

  1. 将 3 个变量endIndex初始化为 0,将currMaxglobalMax初始化为输入数组的第一个值。
  2. 从索引开始阵列中的每个元件(说ⅰ)1,更新currMaxmax(NUMS [I],NUMS + currMax [I])globalMaxendIndexi只有当currMax> globalMax。
  3. 找到起始索引,从endIndex向左迭代,不断递减globalMax的值,直到变为0,变为0的点就是起始索引。
  4. 现在打印[start, end]之间的子数组。

下面是上述方法的实现:

C++
// C++ program for the above approach
#include 
using namespace std;
 
// Function to print the elements
// of Subarray with maximum sum
void SubarrayWithMaxSum(vector& nums)
{
    // Initialize currMax and globalMax
    // with first value of nums
    int endIndex, currMax = nums[0];
    int globalMax = nums[0];
 
    // Iterate for all the elemensts
    // of the array
    for (int i = 1; i < nums.size(); ++i) {
 
        // Update currMax
        currMax = max(nums[i],
                      nums[i] + currMax);
 
        // Check if currMax is greater
        // than globalMax
        if (currMax > globalMax) {
            globalMax = currMax;
            endIndex = i;
        }
    }
 
    int startIndex = endIndex;
 
    // Traverse in left direction to
    // find start Index of subarray
    while (startIndex >= 0) {
 
        globalMax -= nums[startIndex];
 
        if (globalMax == 0)
            break;
 
        // Decrement the start index
        startIndex--;
    }
 
    // Printing the elements of
    // subarray with max sum
    for (int i = startIndex;
         i <= endIndex; ++i) {
 
        cout << nums[i] << " ";
    }
}
 
// Driver Code
int main()
{
    // Given array arr[]
    vector arr
        = { -2, -5, 6, -2,
            -3, 1, 5, -6 };
 
    // Function call
    SubarrayWithMaxSum(arr);
    return 0;
}


Java
// Java program for the above approach
import java.util.*;
class GFG{
 
  // Function to print the elements
  // of Subarray with maximum sum
  static void SubarrayWithMaxSum(Vector nums)
  {
    // Initialize currMax and globalMax
    // with first value of nums
    int endIndex = 0, currMax = nums.get(0);
    int globalMax = nums.get(0);
 
    // Iterate for all the elemensts
    // of the array
    for (int i = 1; i < nums.size(); ++i)
    {
 
      // Update currMax
      currMax = Math.max(nums.get(i),
                         nums.get(i) + currMax);
 
      // Check if currMax is greater
      // than globalMax
      if (currMax > globalMax)
      {
        globalMax = currMax;
        endIndex = i;
      }
    }
 
    int startIndex = endIndex;
 
    // Traverse in left direction to
    // find start Index of subarray
    while (startIndex >= 0)
    {
      globalMax -= nums.get(startIndex);
 
      if (globalMax == 0)
        break;
 
      // Decrement the start index
      startIndex--;
    }
 
    // Printing the elements of
    // subarray with max sum
    for(int i = startIndex; i <= endIndex; ++i)
    {
      System.out.print(nums.get(i) + " ");
    }
  }
 
  // Driver Code
  public static void main(String[] args)
  {
    // Given array arr[]
    Vector arr = new Vector();
    arr.add(-2);
    arr.add(-5);
    arr.add(6);
    arr.add(-2);
    arr.add(-3);
    arr.add(1);
    arr.add(5);
    arr.add(-6);
 
    // Function call
    SubarrayWithMaxSum(arr);
  }
}
 
// This code is contributed by Rajput-Ji


Python3
# Python3 program for the above approach
 
# Function to print the elements
# of Subarray with maximum sum
def SubarrayWithMaxSum(nums):
     
    # Initialize currMax and globalMax
    # with first value of nums
    currMax = nums[0]
    globalMax = nums[0]
 
    # Iterate for all the elemensts
    # of the array
    for i in range(1, len(nums)):
 
        # Update currMax
        currMax = max(nums[i],
                      nums[i] + currMax)
 
        # Check if currMax is greater
        # than globalMax
        if (currMax > globalMax):
            globalMax = currMax
            endIndex = i
     
    startIndex = endIndex
 
    # Traverse in left direction to
    # find start Index of subarray
    while (startIndex >= 0):
        globalMax -= nums[startIndex]
 
        if (globalMax == 0):
            break
 
        # Decrement the start index
        startIndex -= 1
     
    # Printing the elements of
    # subarray with max sum
    for i in range(startIndex, endIndex + 1):
        print(nums[i], end = " ")
     
# Driver Code
 
# Given array arr[]
arr = [ -2, -5, 6, -2,
        -3, 1, 5, -6 ]
 
# Function call
SubarrayWithMaxSum(arr)
 
# This code is contributed by sanjoy_62


C#
// C# program for the above approach
using System;
using System.Collections.Generic;
class GFG{
 
  // Function to print the elements
  // of Subarray with maximum sum
  static void SubarrayWithMaxSum(List nums)
  {
    // Initialize currMax and globalMax
    // with first value of nums
    int endIndex = 0, currMax = nums[0];
    int globalMax = nums[0];
 
    // Iterate for all the elemensts
    // of the array
    for (int i = 1; i < nums.Count; ++i)
    {
 
      // Update currMax
      currMax = Math.Max(nums[i],
                         nums[i] + currMax);
 
      // Check if currMax is greater
      // than globalMax
      if (currMax > globalMax)
      {
        globalMax = currMax;
        endIndex = i;
      }
    }
 
    int startIndex = endIndex;
 
    // Traverse in left direction to
    // find start Index of subarray
    while (startIndex >= 0)
    {
      globalMax -= nums[startIndex];
 
      if (globalMax == 0)
        break;
 
      // Decrement the start index
      startIndex--;
    }
 
    // Printing the elements of
    // subarray with max sum
    for(int i = startIndex; i <= endIndex; ++i)
    {
      Console.Write(nums[i] + " ");
    }
  }
 
  // Driver Code
  public static void Main(String[] args)
  {
    // Given array []arr
    List arr = new List();
    arr.Add(-2);
    arr.Add(-5);
    arr.Add(6);
    arr.Add(-2);
    arr.Add(-3);
    arr.Add(1);
    arr.Add(5);
    arr.Add(-6);
 
    // Function call
    SubarrayWithMaxSum(arr);
  }
}
 
// This code is contributed by gauravrajput1


Javascript


Java
// Java program for the above approach
import java.util.*;
 
class GFG {
 
    // Function to print the elements
    // of Subarray with maximum sum
    static void SubarrayWithMaxSum(Vector nums)
    {
        // Initialize currMax and globalMax
        // with first value of nums
        int currMax = nums.get(0), globalMax = nums.get(0);
        // Initialize endIndex startIndex,globalStartIndex
        int endIndex = 0;
        int startIndex = 0, globalMaxStartIndex = 0;
 
        // Iterate for all the elemensts of the array
        for (int i = 1; i < nums.size(); ++i) {
 
            // Update currMax and startIndex
            if (nums.get(i) > nums.get(i) + currMax) {
                currMax = nums.get(i);
                startIndex = i; // update the new startIndex
            }
 
            // Update currMax
            else if (nums.get(i) < nums.get(i) + currMax) {
                currMax = nums.get(i) + currMax;
            }
 
            // Update globalMax anf globalMaxStartIndex
            if (currMax > globalMax) {
                globalMax = currMax;
                endIndex = i;
                globalMaxStartIndex = startIndex;
            }
        }
 
        // Printing the elements of subarray with max sum
        for (int i = globalMaxStartIndex; i <= endIndex;
             ++i) {
            System.out.print(nums.get(i) + " ");
        }
    }
 
    // Driver Code
    public static void main(String[] args)
    {
        // Given array arr[]
        Vector arr = new Vector();
        arr.add(-2);
        arr.add(-5);
        arr.add(6);
        arr.add(-2);
        arr.add(-3);
        arr.add(1);
        arr.add(5);
        arr.add(-6);
        // Function call
        SubarrayWithMaxSum(arr);
    }
}
 
// This code is contributed by Amritha Basavaraj Patil


C#
// C# program for the above approach
using System;
using System.Collections.Generic;
 
public class GFG{
    // Function to print the elements
    // of Subarray with maximum sum
    static void SubarrayWithMaxSum(List nums)
    {
        // Initialize currMax and globalMax
        // with first value of nums
        int currMax = nums[0], globalMax = nums[0];
       
        // Initialize endIndex startIndex,globalStartIndex
        int endIndex = 0;
        int startIndex = 0, globalMaxStartIndex = 0;
  
        // Iterate for all the elemensts of the array
        for (int i = 1; i < nums.Count; ++i) {
  
            // Update currMax and startIndex
            if (nums[i] > nums[i] + currMax) {
                currMax = nums[i];
                startIndex = i; // update the new startIndex
            }
  
            // Update currMax
            else if (nums[i] < nums[i] + currMax) {
                currMax = nums[i] + currMax;
            }
  
            // Update globalMax anf globalMaxStartIndex
            if (currMax > globalMax) {
                globalMax = currMax;
                endIndex = i;
                globalMaxStartIndex = startIndex;
            }
        }
  
        // Printing the elements of subarray with max sum
        for (int i = globalMaxStartIndex; i <= endIndex;
             ++i) {
            Console.Write(nums[i] + " ");
        }
    }
  
    // Driver Code
    static public void Main (){
         
        // Given array arr[]
        List arr = new List();
        arr.Add(-2);
        arr.Add(-5);
        arr.Add(6);
        arr.Add(-2);
        arr.Add(-3);
        arr.Add(1);
        arr.Add(5);
        arr.Add(-6);
        // Function call
        SubarrayWithMaxSum(arr);
         
    }
}
 
// This code is contributed by rag2127.


Javascript


输出
6 -2 -3 1 5 

时间复杂度: O(N)
辅助空间: O(1)

替代高效方法:这种方法消除了在上述方法中向左移动减少 global_max 的内部 while 循环。因此这种方法减少了时间。

  1. 将 currMax 和 globalMax 初始化为输入数组的第一个值。将 endIndex, startIndex, globalMaxStartIndex 初始化为 0。( endIndex, startIndex 存储以 i 结尾的最大和子数组的开始和结束索引。 globalMaxStartIndex 存储 globalMax 的 startIndex )
  2. 对于数组中从索引(例如 i)1 开始的每个元素,如果 nums[i] > nums[i] + currMax,则将 currMax 和 startIndex 更新为 i。否则只更新currMax。
  3. 如果 currMax>globalMax,则更新 globalMax。同时更新 globalMaxStartIndex。
  4. 现在打印 [start index, globalMaxStartIndex] 之间的子数组。

下面是上述方法的实现:

Java

// Java program for the above approach
import java.util.*;
 
class GFG {
 
    // Function to print the elements
    // of Subarray with maximum sum
    static void SubarrayWithMaxSum(Vector nums)
    {
        // Initialize currMax and globalMax
        // with first value of nums
        int currMax = nums.get(0), globalMax = nums.get(0);
        // Initialize endIndex startIndex,globalStartIndex
        int endIndex = 0;
        int startIndex = 0, globalMaxStartIndex = 0;
 
        // Iterate for all the elemensts of the array
        for (int i = 1; i < nums.size(); ++i) {
 
            // Update currMax and startIndex
            if (nums.get(i) > nums.get(i) + currMax) {
                currMax = nums.get(i);
                startIndex = i; // update the new startIndex
            }
 
            // Update currMax
            else if (nums.get(i) < nums.get(i) + currMax) {
                currMax = nums.get(i) + currMax;
            }
 
            // Update globalMax anf globalMaxStartIndex
            if (currMax > globalMax) {
                globalMax = currMax;
                endIndex = i;
                globalMaxStartIndex = startIndex;
            }
        }
 
        // Printing the elements of subarray with max sum
        for (int i = globalMaxStartIndex; i <= endIndex;
             ++i) {
            System.out.print(nums.get(i) + " ");
        }
    }
 
    // Driver Code
    public static void main(String[] args)
    {
        // Given array arr[]
        Vector arr = new Vector();
        arr.add(-2);
        arr.add(-5);
        arr.add(6);
        arr.add(-2);
        arr.add(-3);
        arr.add(1);
        arr.add(5);
        arr.add(-6);
        // Function call
        SubarrayWithMaxSum(arr);
    }
}
 
// This code is contributed by Amritha Basavaraj Patil

C#

// C# program for the above approach
using System;
using System.Collections.Generic;
 
public class GFG{
    // Function to print the elements
    // of Subarray with maximum sum
    static void SubarrayWithMaxSum(List nums)
    {
        // Initialize currMax and globalMax
        // with first value of nums
        int currMax = nums[0], globalMax = nums[0];
       
        // Initialize endIndex startIndex,globalStartIndex
        int endIndex = 0;
        int startIndex = 0, globalMaxStartIndex = 0;
  
        // Iterate for all the elemensts of the array
        for (int i = 1; i < nums.Count; ++i) {
  
            // Update currMax and startIndex
            if (nums[i] > nums[i] + currMax) {
                currMax = nums[i];
                startIndex = i; // update the new startIndex
            }
  
            // Update currMax
            else if (nums[i] < nums[i] + currMax) {
                currMax = nums[i] + currMax;
            }
  
            // Update globalMax anf globalMaxStartIndex
            if (currMax > globalMax) {
                globalMax = currMax;
                endIndex = i;
                globalMaxStartIndex = startIndex;
            }
        }
  
        // Printing the elements of subarray with max sum
        for (int i = globalMaxStartIndex; i <= endIndex;
             ++i) {
            Console.Write(nums[i] + " ");
        }
    }
  
    // Driver Code
    static public void Main (){
         
        // Given array arr[]
        List arr = new List();
        arr.Add(-2);
        arr.Add(-5);
        arr.Add(6);
        arr.Add(-2);
        arr.Add(-3);
        arr.Add(1);
        arr.Add(5);
        arr.Add(-6);
        // Function call
        SubarrayWithMaxSum(arr);
         
    }
}
 
// This code is contributed by rag2127.

Javascript


输出
6 -2 -3 1 5 

时间复杂度: O(N)  
辅助空间: O(1)

如果您希望与专家一起参加现场课程,请参阅DSA 现场工作专业课程学生竞争性编程现场课程