给定两个数组的所有索引的前缀和的最大差异
给定 2 个大小为N的整数数组a[]和s[] 。任务是找到给定数组的所有索引的前缀和的最大差异。
例子:
Input: N = 5, a[] = {20, 20, 35, 20, 35}, s[] = {21, 31, 34, 41, 14}
Output: 32
Explanation: After prefix sum the arrays are a[] = {20, 40, 75, 95, 130}
and b[] = {21, 52, 86, 127, 141} for S. The maximum difference is (127 – 95) = 32 for 4th position.
Input: N = 1, a[] = {32}, s[] = {15}
Output: A, 17
Explanation: The highest difference (since only one element) is 32 – 15 = 17.
方法:这个问题可以通过计算两个数组中的前缀和然后比较每个索引的差异来解决。请按照以下步骤解决问题:
- 使用变量i遍历范围[0, n)并计算两个数组的前缀和。
- 计算每个索引的前缀和之差。
- 返回最大差异。
下面是上述方法的实现。
C++
// C++ program for the above approach
#include
using namespace std;
// Function to get the winner
int getWinner(int a[], int s[], int N)
{
int maxDiff = abs(a[0] - s[0]);
// Calculating prefix sum
for (int i = 1; i < N; i++) {
a[i] += a[i - 1];
s[i] += s[i - 1];
maxDiff = max(maxDiff,
abs(a[i] - s[i]));
}
// Return the result
return maxDiff;
}
// Driver Code
int main()
{
int N = 5;
int a[] = { 20, 20, 35, 20, 35 },
s[] = { 21, 31, 34, 41, 14 };
cout << getWinner(a, s, N);
return 0;
}
Java
// Java program for the above approach
class GFG{
// Function to get the winner
static int getWinner(int a[], int s[], int N)
{
int maxDiff = Math.abs(a[0] - s[0]);
// Calculating prefix sum
for (int i = 1; i < N; i++) {
a[i] += a[i - 1];
s[i] += s[i - 1];
maxDiff = Math.max(maxDiff,
Math.abs(a[i] - s[i]));
}
// Return the result
return maxDiff;
}
// Driver Code
public static void main(String[] args)
{
int N = 5;
int a[] = { 20, 20, 35, 20, 35 },
s[] = { 21, 31, 34, 41, 14 };
System.out.print(getWinner(a, s, N));
}
}
// This code is contributed by Rajput-Ji
Python3
# python3 program for the above approach
# Function to get the winner
def getWinner(a, s, N):
maxDiff = abs(a[0] - s[0])
# Calculating prefix sum
for i in range(1, N):
a[i] += a[i - 1]
s[i] += s[i - 1]
maxDiff = max(maxDiff, abs(a[i] - s[i]))
# Return the result
return maxDiff
# Driver Code
if __name__ == "__main__":
N = 5
a = [20, 20, 35, 20, 35]
s = [21, 31, 34, 41, 14]
print(getWinner(a, s, N))
# This code is contributed by rakeshsahni
C#
// C# program for the above approach
using System;
class GFG {
// Function to get the winner
static int getWinner(int[] a, int[] s, int N)
{
int maxDiff = Math.Abs(a[0] - s[0]);
// Calculating prefix sum
for (int i = 1; i < N; i++) {
a[i] += a[i - 1];
s[i] += s[i - 1];
maxDiff
= Math.Max(maxDiff, Math.Abs(a[i] - s[i]));
}
// Return the result
return maxDiff;
}
// Driver Code
public static void Main(string[] args)
{
int N = 5;
int[] a = { 20, 20, 35, 20, 35 };
int[] s = { 21, 31, 34, 41, 14 };
Console.WriteLine(getWinner(a, s, N));
}
}
// This code is contributed by ukasp.
Javascript
输出
32
时间复杂度: O(N)
辅助空间: O(1)