📜  打印最大子数组总和

📅  最后修改于: 2021-05-18 00:19:40             🧑  作者: Mango

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

例子:

天真的方法:天真的方法是生成所有可能的子数组并打印具有最大和的子数组。

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

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

  1. 将3个变量endIndex初始化为0,将currMaxglobalMax初始化为输入数组的第一个值。
  2. 对于从index(say i )1开始的数组中的每个元素,仅当currMax> globalMax时,将currMax更新为max(nums [i],nums [i] + currMax)并将globalMaxendIndex更新i
  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


输出:
6 -2 -3 1 5

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