📜  查找取数组中每个第K个元素的最大和

📅  最后修改于: 2021-04-24 04:01:20             🧑  作者: Mango

给定一个由整数和整数K组成的数组arr [] ,任务是找到每K元素的最大和,即sum = arr [i] + arr [i + k] + arr [i + 2 * k] + arr [i + 3 * k] +…。 arr [i + q * k]以任何i开头。

例子:

天真的方法:通过使用两个嵌套循环并从索引i开始找到每个序列的总和,然后将每个K元素相加直到n ,然后从所有这些中找到最大值,来解决这个问题。该方法的时间复杂度为O(N 2 )

下面是上述方法的实现:

C++
// C++ implementation of the approach
#include 
using namespace std;
  
// Function to return the maximum sum for
// every possible sequence such that
// a[i] + a[i+k] + a[i+2k] + ... + a[i+qk]
// is maximized
int maxSum(int arr[], int n, int K)
{
  
    // Initialize the maximum with
    // the smallest value
    int maximum = INT_MIN;
  
    // Find maximum from all sequences
    for (int i = 0; i < n; i++) {
  
        int sumk = 0;
  
        // Sum of the sequence
        // starting from index i
        for (int j = i; j < n; j += K)
            sumk = sumk + arr[j];
  
        // Update maximum
        maximum = max(maximum, sumk);
    }
  
    return maximum;
}
  
// Driver code
int main()
{
    int arr[] = { 3, 6, 4, 7, 2 };
    int n = sizeof(arr) / sizeof(arr[0]);
    int K = 2;
  
    cout << maxSum(arr, n, K);
  
    return (0);
}


Java
// Java implementation of the approach
class GFG
{
      
// Function to return the maximum sum for
// every possible sequence such that
// a[i] + a[i+k] + a[i+2k] + ... + a[i+qk]
// is maximized
static int maxSum(int arr[], int n, int K)
{
  
    // Initialize the maximum with
    // the smallest value
    int maximum = Integer.MIN_VALUE;
  
    // Find maximum from all sequences
    for (int i = 0; i < n; i++) 
    {
  
        int sumk = 0;
  
        // Sum of the sequence
        // starting from index i
        for (int j = i; j < n; j += K)
            sumk = sumk + arr[j];
  
        // Update maximum
        maximum = Math.max(maximum, sumk);
    }
  
    return maximum;
}
  
// Driver code
public static void main(String[] args)
{
    int arr[] = { 3, 6, 4, 7, 2 };
    int n = arr.length;
    int K = 2;
  
    System.out.println(maxSum(arr, n, K));
}
}
  
// This code is contributed by Code_Mech


Python3
# Python 3 implementation of the approach
import sys
  
# Function to return the maximum sum for
# every possible sequence such that
# a[i] + a[i+k] + a[i+2k] + ... + a[i+qk]
# is maximized
def maxSum(arr, n, K):
      
    # Initialize the maximum with
    # the smallest value
    maximum = -sys.maxsize - 1
  
    # Find maximum from all sequences
    for i in range(n):
        sumk = 0
  
        # Sum of the sequence
        # starting from index i
        for j in range(i, n, K):
            sumk = sumk + arr[j]
  
        # Update maximum
        maximum = max(maximum, sumk)
  
    return maximum
  
# Driver code
if __name__ == '__main__':
    arr = [3, 6, 4, 7, 2]
    n = len(arr)
    K = 2
    print(maxSum(arr, n, K))
      
# This code is contributed by
# Surendra_Gangwar


C#
// C# implementation of the approach
using System;
  
class GFG
{
      
// Function to return the maximum sum for
// every possible sequence such that
// a[i] + a[i+k] + a[i+2k] + ... + a[i+qk]
// is maximized
static int maxSum(int []arr, int n, int K)
{
  
    // Initialize the maximum with
    // the smallest value
    int maximum = int.MinValue;
  
    // Find maximum from all sequences
    for (int i = 0; i < n; i++) 
    {
  
        int sumk = 0;
  
        // Sum of the sequence
        // starting from index i
        for (int j = i; j < n; j += K)
            sumk = sumk + arr[j];
  
        // Update maximum
        maximum = Math.Max(maximum, sumk);
    }
  
    return maximum;
}
  
// Driver code
public static void Main()
{
    int []arr = { 3, 6, 4, 7, 2 };
    int n = arr.Length;
    int K = 2;
  
    Console.WriteLine(maxSum(arr, n, K));
}
}
  
// This code is contributed by Akanksha Rai


PHP


C++
// C++ implementation of the approach
#include 
using namespace std;
  
// Function to return the maximum sum for
// every possible sequence such that
// a[i] + a[i+k] + a[i+2k] + ... + a[i+qk]
// is maximized
int maxSum(int arr[], int n, int K)
{
  
    // Initialize the maximum with
    // the smallest value
    int maximum = INT_MIN;
  
    // Initialize the sum array with zero
    int sum[n] = { 0 };
  
    // Iterate from the right
    for (int i = n - 1; i >= 0; i--) {
  
        // Update the sum starting at
        // the current element
        if (i + K < n)
            sum[i] = sum[i + K] + arr[i];
        else
            sum[i] = arr[i];
  
        // Update the maximum so far
        maximum = max(maximum, sum[i]);
    }
  
    return maximum;
}
  
// Driver code
int main()
{
    int arr[] = { 3, 6, 4, 7, 2 };
    int n = sizeof(arr) / sizeof(arr[0]);
    int K = 2;
  
    cout << maxSum(arr, n, K);
  
    return (0);
}


Java
// Java implementation of the approach
class GFG {
  
    // Function to return the maximum sum for
    // every possible sequence such that
    // a[i] + a[i+k] + a[i+2k] + ... + a[i+qk]
    // is maximized
    static int maxSum(int arr[], int n, int K)
    {
  
        // Initialize the maximum with
        // the smallest value
        int maximum = Integer.MIN_VALUE;
  
        // Initialize the sum array with zero
        int[] sum = new int[n];
  
        // Iterate from the right
        for (int i = n - 1; i >= 0; i--) {
  
            // Update the sum starting at
            // the current element
            if (i + K < n)
                sum[i] = sum[i + K] + arr[i];
            else
                sum[i] = arr[i];
  
            // Update the maximum so far
            maximum = Math.max(maximum, sum[i]);
        }
  
        return maximum;
    }
  
    // Driver code
    public static void main(String[] args)
    {
        int arr[] = { 3, 6, 4, 7, 2 };
        int n = arr.length;
        int K = 2;
  
        System.out.print(maxSum(arr, n, K));
    }
}


Python
# Python implementation of the approach
  
# Function to return the maximum sum for
# every possible sequence such that 
# a[i] + a[i + k] + a[i + 2k] + ... + a[i + qk] 
# is maximized
def maxSum(arr, n, K):
      
    # Initialize the maximum with 
    # the smallest value
    maximum = -2**32;
  
    # Initialize the sum array with zero
    sum = [0]*n
  
    # Iterate from the right
    for i in range(n-1, -1, -1):
          
        # Update the sum starting at 
        # the current element
        if( i + K < n ):
            sum[i] = sum[i + K] + arr[i]
        else:
            sum[i] = arr[i];
      
        # Update the maximum so far
        maximum = max( maximum, sum[i] )
      
    return maximum;
  
# Driver code
arr = [3, 6, 4, 7, 2]
n = len(arr);
K = 2
print(maxSum(arr, n, K))


C#
// C# implementation of the approach
using System;
class GFG {
  
    // Function to return the maximum sum for
    // every possible sequence such that
    // a[i] + a[i+k] + a[i+2k] + ... + a[i+qk]
    // is maximized
    static int maxSum(int[] arr, int n, int K)
    {
  
        // Initialize the maximum with
        // the smallest value
        int maximum = int.MinValue;
  
        // Initialize the sum array with zero
        int[] sum = new int[n];
  
        // Iterate from the right
        for (int i = n - 1; i >= 0; i--) {
  
            // Update the sum starting at
            // the current element
            if (i + K < n)
                sum[i] = sum[i + K] + arr[i];
            else
                sum[i] = arr[i];
  
            // Update the maximum so far
            maximum = Math.Max(maximum, sum[i]);
        }
  
        return maximum;
    }
  
    // Driver code
    public static void Main()
    {
        int[] arr = { 3, 6, 4, 7, 2 };
        int n = arr.Length;
        int K = 2;
  
        Console.Write(maxSum(arr, n, K));
    }
}


PHP
= 0; $i--) 
    {
  
        // Update the sum starting at
        // the current element
        if ($i + $K < $n)
            $sum[$i] = $sum[$i + $K] + $arr[$i];
        else
            $sum[$i] = $arr[$i];
  
        // Update the maximum so far
        $maximum = max($maximum, $sum[$i]);
    }
  
    return $maximum;
}
  
// Driver code
{
    $arr = array(3, 6, 4, 7, 2 );
    $n = sizeof($arr);
    $K = 2;
  
    echo(maxSum($arr, $n, $K));
}
  
// This code is contributed by Learner_


输出:
13

高效的方法:这个问题可以通过使用后缀数组的概念来解决,我们从右侧迭代数组,并存储第(i + k)个元素的后缀和(即,i + k ,并且找到最大的和。此方法的时间复杂度为O(N)。

下面是上述方法的实现。

C++

// C++ implementation of the approach
#include 
using namespace std;
  
// Function to return the maximum sum for
// every possible sequence such that
// a[i] + a[i+k] + a[i+2k] + ... + a[i+qk]
// is maximized
int maxSum(int arr[], int n, int K)
{
  
    // Initialize the maximum with
    // the smallest value
    int maximum = INT_MIN;
  
    // Initialize the sum array with zero
    int sum[n] = { 0 };
  
    // Iterate from the right
    for (int i = n - 1; i >= 0; i--) {
  
        // Update the sum starting at
        // the current element
        if (i + K < n)
            sum[i] = sum[i + K] + arr[i];
        else
            sum[i] = arr[i];
  
        // Update the maximum so far
        maximum = max(maximum, sum[i]);
    }
  
    return maximum;
}
  
// Driver code
int main()
{
    int arr[] = { 3, 6, 4, 7, 2 };
    int n = sizeof(arr) / sizeof(arr[0]);
    int K = 2;
  
    cout << maxSum(arr, n, K);
  
    return (0);
}

Java

// Java implementation of the approach
class GFG {
  
    // Function to return the maximum sum for
    // every possible sequence such that
    // a[i] + a[i+k] + a[i+2k] + ... + a[i+qk]
    // is maximized
    static int maxSum(int arr[], int n, int K)
    {
  
        // Initialize the maximum with
        // the smallest value
        int maximum = Integer.MIN_VALUE;
  
        // Initialize the sum array with zero
        int[] sum = new int[n];
  
        // Iterate from the right
        for (int i = n - 1; i >= 0; i--) {
  
            // Update the sum starting at
            // the current element
            if (i + K < n)
                sum[i] = sum[i + K] + arr[i];
            else
                sum[i] = arr[i];
  
            // Update the maximum so far
            maximum = Math.max(maximum, sum[i]);
        }
  
        return maximum;
    }
  
    // Driver code
    public static void main(String[] args)
    {
        int arr[] = { 3, 6, 4, 7, 2 };
        int n = arr.length;
        int K = 2;
  
        System.out.print(maxSum(arr, n, K));
    }
}

Python

# Python implementation of the approach
  
# Function to return the maximum sum for
# every possible sequence such that 
# a[i] + a[i + k] + a[i + 2k] + ... + a[i + qk] 
# is maximized
def maxSum(arr, n, K):
      
    # Initialize the maximum with 
    # the smallest value
    maximum = -2**32;
  
    # Initialize the sum array with zero
    sum = [0]*n
  
    # Iterate from the right
    for i in range(n-1, -1, -1):
          
        # Update the sum starting at 
        # the current element
        if( i + K < n ):
            sum[i] = sum[i + K] + arr[i]
        else:
            sum[i] = arr[i];
      
        # Update the maximum so far
        maximum = max( maximum, sum[i] )
      
    return maximum;
  
# Driver code
arr = [3, 6, 4, 7, 2]
n = len(arr);
K = 2
print(maxSum(arr, n, K))

C#

// C# implementation of the approach
using System;
class GFG {
  
    // Function to return the maximum sum for
    // every possible sequence such that
    // a[i] + a[i+k] + a[i+2k] + ... + a[i+qk]
    // is maximized
    static int maxSum(int[] arr, int n, int K)
    {
  
        // Initialize the maximum with
        // the smallest value
        int maximum = int.MinValue;
  
        // Initialize the sum array with zero
        int[] sum = new int[n];
  
        // Iterate from the right
        for (int i = n - 1; i >= 0; i--) {
  
            // Update the sum starting at
            // the current element
            if (i + K < n)
                sum[i] = sum[i + K] + arr[i];
            else
                sum[i] = arr[i];
  
            // Update the maximum so far
            maximum = Math.Max(maximum, sum[i]);
        }
  
        return maximum;
    }
  
    // Driver code
    public static void Main()
    {
        int[] arr = { 3, 6, 4, 7, 2 };
        int n = arr.Length;
        int K = 2;
  
        Console.Write(maxSum(arr, n, K));
    }
}

的PHP

= 0; $i--) 
    {
  
        // Update the sum starting at
        // the current element
        if ($i + $K < $n)
            $sum[$i] = $sum[$i + $K] + $arr[$i];
        else
            $sum[$i] = $arr[$i];
  
        // Update the maximum so far
        $maximum = max($maximum, $sum[$i]);
    }
  
    return $maximum;
}
  
// Driver code
{
    $arr = array(3, 6, 4, 7, 2 );
    $n = sizeof($arr);
    $K = 2;
  
    echo(maxSum($arr, $n, $K));
}
  
// This code is contributed by Learner_
输出:
13

时间复杂度: O(N),其中N是数组中元素的数量。