📌  相关文章
📜  用接下来的K个元素的总和替换圆形数组中的每个元素

📅  最后修改于: 2021-05-14 00:01:20             🧑  作者: Mango

给定一个由N个整数和一个整数K组成的圆形数组arr [] ,任务是在执行以下操作后打印该数组:

  • 如果K为非负数,则用接下来的K个元素的总和替换A [i]
  • 如果K为负,则将其替换为先前K个元素的总和。

例子:

天真的方法:解决问题的最简单方法是遍历数组,并根据每个数组元素的K值遍历下一个或上一个K元素,并打印它们的和。请按照以下步骤解决问题:

  • 如果K的值为负,则反转数组并找到接下来的K个元素的总和。
  • 如果K的值为非负数,则只需为每个元素找到接下来的K个元素的总和。

下面是上述方法的实现:

C++
// C++ program for the above approach
 
#include 
using namespace std;
#define pb push_back
 
// Function to find the sum of next
// or previous k array elements
vector sumOfKelementsUtil(
    vector& a, int x)
{
    // Size of the array
    int n = a.size();
 
    int count, k, temp;
 
    // Stores the result
    vector ans;
 
    // Iterate the given array
    for (int i = 0; i < n; i++) {
 
        count = 0;
        k = i + 1;
        temp = 0;
 
        // Traverse the k elements
        while (count < x) {
 
            temp += a[k % n];
            count++;
            k++;
        }
 
        // Push the K elements sum
        ans.pb(temp);
    }
 
    // Return the resultant vector
    return ans;
}
 
// Function that prints the sum of next
// K element for each index in the array
void sumOfKelements(vector& arr,
                    int K)
{
    // Size of the array
    int N = (int)arr.size();
 
    // Stores the result
    vector ans;
 
    // If key is negative,
    // reverse the array
    if (K < 0) {
        K = K * (-1);
 
        // Reverse the array
        reverse(arr.begin(),
                arr.end());
 
        // Find the resultant vector
        ans = sumOfKelementsUtil(arr, K);
 
        // Reverse the array again to
        // get the original sequence
        reverse(ans.begin(), ans.end());
    }
 
    // If K is positive
    else {
        ans = sumOfKelementsUtil(arr, K);
    }
 
    // Print the answer
    for (int i = 0; i < N; i++) {
        cout << ans[i] << " ";
    }
}
 
// Driver Code
int main()
{
    // Given array arr[]
    vector arr = { 4, 2, -5, 11 };
    int K = 3;
 
    // Function Calll
    sumOfKelements(arr, K);
 
    return 0;
}


Java
// Java program for
// the above approach
import java.util.*;
class GFG{
     
//reverse array
static Vector reverse(Vector a)
{
  int i, n = a.size(), t;
  for (i = 0; i < n / 2; i++)
  {
    t = a.elementAt(i);
    a.set(i, a.elementAt(n - i - 1));
    a.set(n - i - 1, t);
  }
  return a;
}
 
// Function to find the sum of next
// or previous k array elements
static Vector sumOfKelementsUtil(
       Vectora, int x)
{
  // Size of the array
  int n = a.size();
 
  int count, k, temp;
 
  // Stores the result
  Vector ans = new Vector<>();
 
  // Iterate the given array
  for (int i = 0; i < n; i++)
  {
    count = 0;
    k = i + 1;
    temp = 0;
 
    // Traverse the k elements
    while (count < x)
    {
      temp += a.elementAt(k % n);
      count++;
      k++;
    }
 
    // Push the K elements sum
    ans.add(temp);
  }
 
  // Return the resultant vector
  return ans;
}
 
// Function that prints the sum of next
// K element for each index in the array
static void sumOfKelements(Vector arr,
                           int K)
{
  // Size of the array
  int N = (int)arr.size();
 
  // Stores the result
  Vector ans = new Vector<>();
 
  // If key is negative,
  // reverse the array
  if (K < 0)
  {
    K = K * (-1);
 
    // Reverse the array
    arr =  reverse(arr);
 
    // Find the resultant vector
    ans = sumOfKelementsUtil(arr, K);
 
    // Reverse the array again to
    // get the original sequence
    ans = reverse(ans);
  }
 
  // If K is positive
  else
  {
    ans = sumOfKelementsUtil(arr, K);
  }
 
  // Print the answer
  for (int i = 0; i < N; i++)
  {
    System.out.print(ans.elementAt(i) + " ");
  }
}
 
// Driver Code
public static void main(String[] args)
{
    // Given array arr[]
    Vector arr = new Vector<>();
    arr.add(4);
    arr.add(2);
    arr.add(-5);
    arr.add(11);
    int K = 3;
 
    // Function Calll
    sumOfKelements(arr, K);
 
}
}
 
// This code is contributed by gauravrajput1


Python3
# Python3 program for
# the above approach
 
# Function to find the sum of next
# or previous k array elements
def sumOfKelementsUtil(a, x):
 
    # Size of the array
    n = len(a)
     
    # Stores the result
    ans = []
 
    # Iterate the given array
    for i in range(n):
        count = 0
        k = i + 1
        temp = 0
 
        # Traverse the k elements
        while (count < x):
            temp += a[k % n]
            count += 1
            k += 1
 
        # Push the K elements sum
        ans.append(temp)
    
    # Return the resultant vector
    return ans
 
# Function that prints the
# sum of next K element for
# each index in the array
def sumOfKelements(arr, K):
 
    # Size of the array
    N = len(arr)
 
    #Stores the result
    ans = []
 
    # If key is negative,
    # reverse the array
    if (K < 0):
        K = K * (-1)
 
        # Reverse the array
        arr =  arr.reverse()
         
        # Find the resultant vector
        ans = sumOfKelementsUtil(arr, K)
 
        #Reverse the array again to
        # get the original sequence
        ans = ans.reverse()
 
    # If K is positive
    else:
        ans = sumOfKelementsUtil(arr, K)
   
    # Print the answer
    for i in range(N):
        print (ans[i], end = " ")
    
# Driver Code
if __name__ == "__main__":
   
    # Given array arr[]
    arr = [4, 2, -5, 11]
    K = 3
 
    # Function Calll
    sumOfKelements(arr, K)
 
# This code is contributed by Chitranayal


C#
// C# program for
// the above approach
using System;
using System.Collections.Generic;
class GFG{
     
// Reverse array
static List reverse(List a)
{
  int i, n = a.Count, t;
  for (i = 0; i < n / 2; i++)
  {
    t = a[i];
    a[i] = a[n - i - 1];
    a[n - i - 1] = t;
  }
  return a;
}
 
// Function to find the sum of next
// or previous k array elements
static List sumOfKelementsUtil(
       Lista, int x)
{
  // Size of the array
  int n = a.Count;
 
  int count, k, temp;
 
  // Stores the result
  List ans = new List();
 
  // Iterate the given array
  for (int i = 0; i < n; i++)
  {
    count = 0;
    k = i + 1;
    temp = 0;
 
    // Traverse the k elements
    while (count < x)
    {
      temp += a[k % n];
      count++;
      k++;
    }
 
    // Push the K elements sum
    ans.Add(temp);
  }
 
  // Return the resultant vector
  return ans;
}
 
// Function that prints the sum of next
// K element for each index in the array
static void sumOfKelements(List arr,
                           int K)
{
  // Size of the array
  int N = (int)arr.Count;
 
  // Stores the result
  List ans = new List();
 
  // If key is negative,
  // reverse the array
  if (K < 0)
  {
    K = K * (-1);
 
    // Reverse the array
    arr =  reverse(arr);
 
    // Find the resultant vector
    ans = sumOfKelementsUtil(arr, K);
 
    // Reverse the array again to
    // get the original sequence
    ans = reverse(ans);
  }
 
  // If K is positive
  else
  {
    ans = sumOfKelementsUtil(arr, K);
  }
 
  // Print the answer
  for (int i = 0; i < N; i++)
  {
    Console.Write(ans[i] + " ");
  }
}
 
// Driver Code
public static void Main(String[] args)
{
  // Given array []arr
  List arr = new List();
  arr.Add(4);
  arr.Add(2);
  arr.Add(-5);
  arr.Add(11);
  int K = 3;
 
  // Function Calll
  sumOfKelements(arr, K);
}
}
 
// This code is contributed by Rajput-Ji


C++
// C++ program for the above approach
#include
using namespace std;
 
// Function to print the
// required resultant array
void sumOfKElements(int arr[], int n,
                    int k)
{
     
    // Reverse the array
    bool rev = false;
 
    if (k < 0)
    {
        rev = true;
        k *= -1;
        int l = 0, r = n - 1;
 
        // Traverse the range
        while (l < r)
        {
            int tmp = arr[l];
            arr[l] = arr[r];
            arr[r] = tmp;
            l++;
            r--;
        }
    }
 
    // Store prefix sum
    int dp[n] = {0};
    dp[0] = arr[0];
 
    // Find the prefix sum
    for(int i = 1; i < n; i++)
    {
        dp[i] += dp[i - 1] + arr[i];
    }
 
    // Store the answer
    int ans[n] = {0};
 
    // Calculate the answers
    for(int i = 0; i < n; i++)
    {
        if (i + k < n)
            ans[i] = dp[i + k] - dp[i];
        else
        {
             
            // Count of remaining elements
            int x = k - (n - 1 - i);
 
            // Add the sum of all elements
            // y times
            int y = x / n;
 
            // Add the remaining elements
            int rem = x % n;
 
            // Update ans[i]
            ans[i] = dp[n - 1] - dp[i] +
                 y * dp[n - 1] + (rem - 1 >= 0 ?
                   dp[rem - 1] : 0);
        }
    }
 
    // If array is reversed print
    // ans[] in reverse
    if (rev)
    {
        for(int i = n - 1; i >= 0; i--)
        {
            cout << ans[i] << " ";
        }
    }
    else
    {
        for(int i = 0; i < n; i++)
        {
            cout << ans[i] << " ";
        }
    }
}
 
// Driver Code
int main()
{
     
    // Given array arr[]
    int arr[] = { 4, 2, -5, 11 };
 
    int N = sizeof(arr) / sizeof(arr[0]);
 
    // Given K
    int K = 3;
 
    // Function
    sumOfKElements(arr, N, K);
}
 
// This code is contributed by SURENDRA_GANGWAR


Java
// Java program for the above approach
import java.io.*;
 
class GFG {
 
    // Function to print the
    // required resultant array
    static void sumOfKElements(
        int arr[], int n, int k)
    {
 
        // Reverse the array
        boolean rev = false;
 
        if (k < 0) {
 
            rev = true;
            k *= -1;
            int l = 0, r = n - 1;
 
            // Traverse the range
            while (l < r) {
 
                int tmp = arr[l];
                arr[l] = arr[r];
                arr[r] = tmp;
                l++;
                r--;
            }
        }
 
        // Store prefix sum
        int dp[] = new int[n];
        dp[0] = arr[0];
 
        // Find the prefix sum
        for (int i = 1; i < n; i++) {
 
            dp[i] += dp[i - 1] + arr[i];
        }
 
        // Store the answer
        int ans[] = new int[n];
 
        // Calculate the answers
        for (int i = 0; i < n; i++) {
 
            if (i + k < n)
                ans[i] = dp[i + k] - dp[i];
            else {
 
                // Count of remaining elements
                int x = k - (n - 1 - i);
 
                // Add the sum of all elements
                // y times
                int y = x / n;
 
                // Add the remaining elements
                int rem = x % n;
 
                // Update ans[i]
                ans[i] = dp[n - 1]
                         - dp[i]
                         + y * dp[n - 1]
                         + (rem - 1 >= 0 ? dp[rem - 1] : 0);
            }
        }
 
        // If array is reversed print
        // ans[] in reverse
        if (rev) {
            for (int i = n - 1; i >= 0; i--) {
                System.out.print(ans[i] + " ");
            }
        }
        else {
            for (int i = 0; i < n; i++) {
                System.out.print(ans[i] + " ");
            }
        }
    }
 
    // Driver Code
    public static void main(String[] args)
    {
        // Given array arr[]
        int arr[] = { 4, 2, -5, 11 };
 
        int N = arr.length;
 
        // Given K
        int K = 3;
 
        // Function
        sumOfKElements(arr, N, K);
    }
}


Python3
# Python3 program for
# the above approach
 
# Function to prthe
# required resultant array
def sumOfKElements(arr, n, k):
   
    # Reverse the array
    rev = False;
 
    if (k < 0):
 
        rev = True;
        k *= -1;
        l = 0;
        r = n - 1;
 
        # Traverse the range
        while (l < r):
            tmp = arr[l];
            arr[l] = arr[r];
            arr[r] = tmp;
            l += 1;
            r -= 1;
 
    # Store prefix sum
    dp = [0] * n;
    dp[0] = arr[0];
 
    # Find the prefix sum
    for i in range(1, n):
        dp[i] += dp[i - 1] + arr[i];
 
    # Store the answer
    ans = [0] * n;
 
    # Calculate the answers
    for i in range(n):
        if (i + k < n):
            ans[i] = dp[i + k] - dp[i];
        else:
 
            # Count of remaining
            # elements
            x = k - (n - 1 - i);
 
            # Add the sum of
            # all elements y times
            y = x // n;
 
            # Add the remaining
            # elements
            rem = x % n;
 
            # Update ans[i]
            ans[i] = (dp[n - 1] - dp[i] +
                      y * dp[n - 1] +
                      (dp[rem - 1]
                      if rem - 1 >= 0
                      else 0));
 
    # If array is reversed
    # print ans in reverse
    if (rev):
        for i in range(n - 1, -1, -1):
            print(ans[i], end = " ");
 
    else:
        for i in range(n):
            print(ans[i], end = " ");
 
# Driver Code
if __name__ == '__main__':
   
    # Given array arr
    arr = [4, 2, -5, 11];
 
    N = len(arr);
 
    # Given K
    K = 3;
 
    # Function
    sumOfKElements(arr, N, K);
 
# This code is contributed by 29AjayKumar


C#
// C# program for
// the above approach
using System;
class GFG {
 
// Function to print the
// required resultant array
static void sumOfKElements(int []arr,
                           int n, int k)
{
  // Reverse the array
  bool rev = false;
 
  if (k < 0)
  {
    rev = true;
    k *= -1;
    int l = 0, r = n - 1;
 
    // Traverse the range
    while (l < r)
    {
      int tmp = arr[l];
      arr[l] = arr[r];
      arr[r] = tmp;
      l++;
      r--;
    }
  }
 
  // Store prefix sum
  int []dp = new int[n];
  dp[0] = arr[0];
 
  // Find the prefix sum
  for (int i = 1; i < n; i++)
  {
    dp[i] += dp[i - 1] + arr[i];
  }
 
  // Store the answer
  int []ans = new int[n];
 
  // Calculate the answers
  for (int i = 0; i < n; i++)
  {
    if (i + k < n)
      ans[i] = dp[i + k] - dp[i];
    else
    {
      // Count of remaining elements
      int x = k - (n - 1 - i);
 
      // Add the sum of all elements
      // y times
      int y = x / n;
 
      // Add the remaining elements
      int rem = x % n;
 
      // Update ans[i]
      ans[i] = dp[n - 1] - dp[i] +
               y * dp[n - 1] +
               (rem - 1 >= 0 ?
                dp[rem - 1] : 0);
    }
  }
 
  // If array is reversed print
  // ans[] in reverse
  if (rev)
  {
    for (int i = n - 1; i >= 0; i--)
    {
      Console.Write(ans[i] + " ");
    }
  }
  else
  {
    for (int i = 0; i < n; i++)
    {
      Console.Write(ans[i] + " ");
    }
  }
}
 
// Driver Code
public static void Main(String[] args)
{
  // Given array []arr
  int []arr = {4, 2, -5, 11};
 
  int N = arr.Length;
 
  // Given K
  int K = 3;
 
  // Function
  sumOfKElements(arr, N, K);
}
}
 
// This code is contributed by Princi Singh


输出
8 10 17 1 





时间复杂度: O(N * K),其中N是给定数组的长度,K是给定整数。
辅助空间: O(N)

高效方法:为了优化上述方法,其思想是使用前缀和。请按照以下步骤解决问题:

  1. 如果K为负,则反转给定数组并将K乘以-1
  2. 计算给定数组的前缀和并将其存储在pre []中
  3. 创建数组ans []来存储每个元素的答案。
  4. 对于每个索引i ,如果i + K小于N ,则更新ans [i] = pre [i + k] – pre [i]
  5. 否则,将所有从索引iN – 1的元素的总和相加,找到剩余的K –(N – 1 – i)个元素,因为在上述步骤中已经添加了(N – 1 – i)个元素。
  6. 将所有元素的总和相加((K – N – 1 – i)/ N)次,并将给定数组的剩余元素之和从0((K –(N – 1 – i))%N)– 1
  7. 在计算完数组中每个元素的答案之后,请检查数组是否先前已反转。如果是,请反转ans []数组。
  8. 完成上述步骤后,打印存储在数组ans []中的所有元素。

下面是上述方法的实现:

C++

// C++ program for the above approach
#include
using namespace std;
 
// Function to print the
// required resultant array
void sumOfKElements(int arr[], int n,
                    int k)
{
     
    // Reverse the array
    bool rev = false;
 
    if (k < 0)
    {
        rev = true;
        k *= -1;
        int l = 0, r = n - 1;
 
        // Traverse the range
        while (l < r)
        {
            int tmp = arr[l];
            arr[l] = arr[r];
            arr[r] = tmp;
            l++;
            r--;
        }
    }
 
    // Store prefix sum
    int dp[n] = {0};
    dp[0] = arr[0];
 
    // Find the prefix sum
    for(int i = 1; i < n; i++)
    {
        dp[i] += dp[i - 1] + arr[i];
    }
 
    // Store the answer
    int ans[n] = {0};
 
    // Calculate the answers
    for(int i = 0; i < n; i++)
    {
        if (i + k < n)
            ans[i] = dp[i + k] - dp[i];
        else
        {
             
            // Count of remaining elements
            int x = k - (n - 1 - i);
 
            // Add the sum of all elements
            // y times
            int y = x / n;
 
            // Add the remaining elements
            int rem = x % n;
 
            // Update ans[i]
            ans[i] = dp[n - 1] - dp[i] +
                 y * dp[n - 1] + (rem - 1 >= 0 ?
                   dp[rem - 1] : 0);
        }
    }
 
    // If array is reversed print
    // ans[] in reverse
    if (rev)
    {
        for(int i = n - 1; i >= 0; i--)
        {
            cout << ans[i] << " ";
        }
    }
    else
    {
        for(int i = 0; i < n; i++)
        {
            cout << ans[i] << " ";
        }
    }
}
 
// Driver Code
int main()
{
     
    // Given array arr[]
    int arr[] = { 4, 2, -5, 11 };
 
    int N = sizeof(arr) / sizeof(arr[0]);
 
    // Given K
    int K = 3;
 
    // Function
    sumOfKElements(arr, N, K);
}
 
// This code is contributed by SURENDRA_GANGWAR

Java

// Java program for the above approach
import java.io.*;
 
class GFG {
 
    // Function to print the
    // required resultant array
    static void sumOfKElements(
        int arr[], int n, int k)
    {
 
        // Reverse the array
        boolean rev = false;
 
        if (k < 0) {
 
            rev = true;
            k *= -1;
            int l = 0, r = n - 1;
 
            // Traverse the range
            while (l < r) {
 
                int tmp = arr[l];
                arr[l] = arr[r];
                arr[r] = tmp;
                l++;
                r--;
            }
        }
 
        // Store prefix sum
        int dp[] = new int[n];
        dp[0] = arr[0];
 
        // Find the prefix sum
        for (int i = 1; i < n; i++) {
 
            dp[i] += dp[i - 1] + arr[i];
        }
 
        // Store the answer
        int ans[] = new int[n];
 
        // Calculate the answers
        for (int i = 0; i < n; i++) {
 
            if (i + k < n)
                ans[i] = dp[i + k] - dp[i];
            else {
 
                // Count of remaining elements
                int x = k - (n - 1 - i);
 
                // Add the sum of all elements
                // y times
                int y = x / n;
 
                // Add the remaining elements
                int rem = x % n;
 
                // Update ans[i]
                ans[i] = dp[n - 1]
                         - dp[i]
                         + y * dp[n - 1]
                         + (rem - 1 >= 0 ? dp[rem - 1] : 0);
            }
        }
 
        // If array is reversed print
        // ans[] in reverse
        if (rev) {
            for (int i = n - 1; i >= 0; i--) {
                System.out.print(ans[i] + " ");
            }
        }
        else {
            for (int i = 0; i < n; i++) {
                System.out.print(ans[i] + " ");
            }
        }
    }
 
    // Driver Code
    public static void main(String[] args)
    {
        // Given array arr[]
        int arr[] = { 4, 2, -5, 11 };
 
        int N = arr.length;
 
        // Given K
        int K = 3;
 
        // Function
        sumOfKElements(arr, N, K);
    }
}

Python3

# Python3 program for
# the above approach
 
# Function to prthe
# required resultant array
def sumOfKElements(arr, n, k):
   
    # Reverse the array
    rev = False;
 
    if (k < 0):
 
        rev = True;
        k *= -1;
        l = 0;
        r = n - 1;
 
        # Traverse the range
        while (l < r):
            tmp = arr[l];
            arr[l] = arr[r];
            arr[r] = tmp;
            l += 1;
            r -= 1;
 
    # Store prefix sum
    dp = [0] * n;
    dp[0] = arr[0];
 
    # Find the prefix sum
    for i in range(1, n):
        dp[i] += dp[i - 1] + arr[i];
 
    # Store the answer
    ans = [0] * n;
 
    # Calculate the answers
    for i in range(n):
        if (i + k < n):
            ans[i] = dp[i + k] - dp[i];
        else:
 
            # Count of remaining
            # elements
            x = k - (n - 1 - i);
 
            # Add the sum of
            # all elements y times
            y = x // n;
 
            # Add the remaining
            # elements
            rem = x % n;
 
            # Update ans[i]
            ans[i] = (dp[n - 1] - dp[i] +
                      y * dp[n - 1] +
                      (dp[rem - 1]
                      if rem - 1 >= 0
                      else 0));
 
    # If array is reversed
    # print ans in reverse
    if (rev):
        for i in range(n - 1, -1, -1):
            print(ans[i], end = " ");
 
    else:
        for i in range(n):
            print(ans[i], end = " ");
 
# Driver Code
if __name__ == '__main__':
   
    # Given array arr
    arr = [4, 2, -5, 11];
 
    N = len(arr);
 
    # Given K
    K = 3;
 
    # Function
    sumOfKElements(arr, N, K);
 
# This code is contributed by 29AjayKumar

C#

// C# program for
// the above approach
using System;
class GFG {
 
// Function to print the
// required resultant array
static void sumOfKElements(int []arr,
                           int n, int k)
{
  // Reverse the array
  bool rev = false;
 
  if (k < 0)
  {
    rev = true;
    k *= -1;
    int l = 0, r = n - 1;
 
    // Traverse the range
    while (l < r)
    {
      int tmp = arr[l];
      arr[l] = arr[r];
      arr[r] = tmp;
      l++;
      r--;
    }
  }
 
  // Store prefix sum
  int []dp = new int[n];
  dp[0] = arr[0];
 
  // Find the prefix sum
  for (int i = 1; i < n; i++)
  {
    dp[i] += dp[i - 1] + arr[i];
  }
 
  // Store the answer
  int []ans = new int[n];
 
  // Calculate the answers
  for (int i = 0; i < n; i++)
  {
    if (i + k < n)
      ans[i] = dp[i + k] - dp[i];
    else
    {
      // Count of remaining elements
      int x = k - (n - 1 - i);
 
      // Add the sum of all elements
      // y times
      int y = x / n;
 
      // Add the remaining elements
      int rem = x % n;
 
      // Update ans[i]
      ans[i] = dp[n - 1] - dp[i] +
               y * dp[n - 1] +
               (rem - 1 >= 0 ?
                dp[rem - 1] : 0);
    }
  }
 
  // If array is reversed print
  // ans[] in reverse
  if (rev)
  {
    for (int i = n - 1; i >= 0; i--)
    {
      Console.Write(ans[i] + " ");
    }
  }
  else
  {
    for (int i = 0; i < n; i++)
    {
      Console.Write(ans[i] + " ");
    }
  }
}
 
// Driver Code
public static void Main(String[] args)
{
  // Given array []arr
  int []arr = {4, 2, -5, 11};
 
  int N = arr.Length;
 
  // Given K
  int K = 3;
 
  // Function
  sumOfKElements(arr, N, K);
}
}
 
// This code is contributed by Princi Singh
输出
8 10 17 1 





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