使用负数最大化集合的两个子集之间的差异
给定一个大小为 N 的整数。任务是将这些整数分成两组 g1 和 g2,使得 (g1 的元素总和) - (g2 的元素总和) 变为最大值。你的任务是打印结果的值。我们可以保留一个子集为空。
例子:
Input : 3, 7, -4, 10, -11, 2
Output : 37
Explanation:
g1: 3, 7, 10, 2
g2: -4, -11
result = ( 3 + 7 + 10 + 2 ) – ( -4 + -11) = 22 – (-15) = 37
Input : 2, 2, -2, -2
Output : 8
这个想法是根据它们的符号值对整数进行分组,即我们将正整数分组为g1,将负整数分组为g2。
因为, – ( -g2 ) = +g2
因此,结果变为 g1 + |g2|。
C++
// CPP program to make two subsets with
// maximum difference.
#include
using namespace std;
int maxDiff(int arr[], int n)
{
int sum = 0;
// We move all negative elements into
// one set. So we add negation of negative
// numbers to maximize difference
for (int i = 0; i < n; i++)
sum = sum + abs(arr[i]);
return sum;
}
// Driver Code
int main()
{
int arr[] = { 3, 7, -4, 10, -11, 2 };
int n = sizeof(arr)/sizeof(arr[0]);
cout << maxDiff(arr, n);
return 0;
}
Java
// Java program to make two subsets with
// maximum difference.
import java.util.*;
class solution
{
static int maxDiff(int arr[], int n)
{
int sum = 0;
// We move all negative elements into
// one set. So we add negation of negative
// numbers to maximize difference
for (int i = 0; i < n; i++)
sum = sum + Math.abs(arr[i]);
return sum;
}
// Driver Code
public static void main(String args[])
{
int []arr = { 3, 7, -4, 10, -11, 2 };
int n = arr.length;
System.out.println(maxDiff(arr, n));
}
}
Python3
# Python3 program to make two subsets
# with maximum difference.
def maxDiff(arr, n) :
sum = 0
# We move all negative elements into
# one set. So we add negation of negative
# numbers to maximize difference
for i in range(n) :
sum += abs(arr[i])
return sum
# Driver Code
if __name__ == "__main__" :
arr = [ 3, 7, -4, 10, -11, 2 ]
n = len(arr)
print(maxDiff(arr, n))
# This code is contributed by Ryuga
C#
using System;
// C# program to make two subsets with
// maximum difference.
public class solution
{
public static int maxDiff(int[] arr, int n)
{
int sum = 0;
// We move all negative elements into
// one set. So we add negation of negative
// numbers to maximize difference
for (int i = 0; i < n; i++)
{
sum = sum + Math.Abs(arr[i]);
}
return sum;
}
// Driver Code
public static void Main(string[] args)
{
int[] arr = new int[] {3, 7, -4, 10, -11, 2};
int n = arr.Length;
Console.WriteLine(maxDiff(arr, n));
}
}
// This code is contributed by Shrikant13
PHP
Javascript
输出:
37
时间复杂度: O(n)