原文:

给定一个数组arr【】,任务是找到具有最大和的相邻数字子数组的元素。

示例:

输入: arr = [-2,-3,4,-1,-2,1,5,-3] 输出:【4,-1,-2,1,5】 解释: 在上述输入中,最大连续子阵列和为 7,子阵列的元素为【4,-1,-2,1,5】

输入: arr = [-2,-5,6,-2,-3,1,5,-6] 输出:【6,-2,-3,1,5】 解释: 在上述输入中,最大连续子阵列和为 7,子阵列的元素 为【6,-2,-3,1,5】

天真方法:天真方法是生成所有可能的子阵列并打印具有最大和的那个子阵列。 时间复杂度:o(n2) 辅助空间: o(1)

高效途径:思路是利用找到最大子阵和,并存储具有最大和的子阵的起始和结束索引,打印从起始索引到结束索引的子阵。以下是步骤:

  1. 将 3 个变量 endindex 初始化为 0, currmaxglobalmax 初始化为输入数组的第一个值。
  2. 对于数组中从索引(比如 i ) 1 开始的每个元素,更新 currmaxmax(nums[i],nums[i] currmax)globalmaxendindexi 仅当 currmax > globalmax 时。
  3. 要找到起始索引,从 endindex 开始向左迭代,并不断递减 globalmax 的值,直到它变成 0。它变为 0 的点是开始索引。
  4. 现在打印【开始,结束】之间的子阵列。

下面是上述方法的实现:

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 elements
    // 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 elements
    // 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

python 3

# 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 elements
    # 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 elements
    // 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

java 描述语言


output

6 -2 -3 1 5 

时间复杂度: o(n) 辅助空间: o(1)

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

  1. 将 currmax 和 globalmax 初始化为输入数组的第一个值。将 endindex、startindex、globalmaxstartindex 初始化为 0。(endindex,startindex 存储以 i 结尾的最大和子数组的开始和结束索引。globalmaxstartindex 存储 globalmax 的开始索引)
  2. 对于数组中从 index(比如 i) 1 开始的每个元素,如果 nums[i] > nums[i] currmax,则将 currmax 和 startindex 更新为 i。否则只更新 currmax。
  3. 如果当前最大值>全局最大值,则更新全局最大值。同时更新 globalmaxstartindex。
  4. 现在打印[开始索引,全局最开始索引]之间的子数组。

以下是上述方法的实现:

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 elements 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 elements 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.

java 描述语言


output

6 -2 -3 1 5 

时间复杂度:*o(n)t5】 t8】辅助空间: o(1)***