Minimum sum of product of two arrays
Last Updated :
14 Jul, 2023
Find the minimum sum of Products of two arrays of the same size, given that k modifications are allowed on the first array. In each modification, one array element of the first array can either be increased or decreased by 2.
Examples:
Input : a[] = {1, 2, -3}
b[] = {-2, 3, -5}
k = 5
Output : -31
Explanation:
Here n = 3 and k = 5.
So, we modified a[2], which is -3 and
increased it by 10 (as 5 modifications
are allowed).
Final sum will be :
(1 * -2) + (2 * 3) + (7 * -5)
-2 + 6 - 35
-31
(which is the minimum sum of the array
with given conditions)
Input : a[] = {2, 3, 4, 5, 4}
b[] = {3, 4, 2, 3, 2}
k = 3
Output : 25
Explanation:
Here, total numbers are 5 and total
modifications allowed are 3. So, modify
a[1], which is 3 and decreased it by 6
(as 3 modifications are allowed).
Final sum will be :
(2 * 3) + (-3 * 4) + (4 * 2) + (5 * 3) + (4 * 2)
6 – 12 + 8 + 15 + 8
25
(which is the minimum sum of the array with
given conditions)
Since we need to minimize the product sum, we find the maximum product and reduce it. By taking some examples, we observe that making 2*k changes to only one element is enough to get the minimum sum. We will further see why this works but first, let us try to understand the intuition behind doing an increase or decrease of 2*k on any element.
If you want to make the sum of all the products as minimum as possible then thinking greedily we will try to minimize the product at every step possible.
a[] = {1, 2, -3}
b[] = {-2, 3, -5}
At index = 0, the original product is (1*-2) = -2 If we want to decrease it further we would try to increase the value of a[0] in order to increase the -ve magnitude
At index = 1, the original product is (2*3) = 6 here there is only one way to decrease the product which is by decreasing a[1] in order to bring the product to -ve or lesser +ve magnitude.
At index = 2, the original product is (-3*-5) = 15, to decrease the product we need to increase a[2] to make the product -ve
Based on the needs we either increase or decrease an element by 2
Why are we applying 2*k operations on a single element only?
The question might have come to your mind why are we applying 2*k operations (either reducing or increasing) on a single element only, why not apply +2 on some ith index and -4 on some jth index and then -2 on some kth index to find out the minimum product sum. Wouldn't there be a possibility that applying operations on different elements fetch us the optimal answer?
Let us try to understand the same with an example
a[] = {-4, -3, 2, 8, 9}
b[] = {7, -6, 4, 2, -3}
K = 3
Now if I apply 2*k operations on my 0th index of a then a[0] = a[0] - 2*k = -10 so the product = -10*7 = -70
Had it been applied in a different manner such as -2 on the 0th index, +2 on the 1th index, and -2 on the 3th index then array a would be a[] ={-6, -1, 2, 6, 9} and the products at respective indices would be -42, 6, and 12 so our overall reduction = -24 which is less than the case when 2*k operations are being applied on a single element.
Just think in the way that if applying an operation on any element decreases your product then applying the rest of the operation on the same element would further decrease your product and eventually your sum and that's the most optimal way.
I would suggest you write down a few test cases of your own and try applying operations in different ways.
Based on this observation, we consider every element as the element on which we apply all k operations and keep track of the element that reduces the result to a minimum.
C++
// CPP program to find minimum sum of product of two arrays
// with k operations allowed on first array.
#include <bits/stdc++.h>
using namespace std;
// Function to find the minimum product
int minproduct(int a[], int b[], int n, int k)
{
int diff = 0, res = 0;
int temp;
for (int i = 0; i < n; i++) {
// Find product of current elements and update
// result.
int pro = a[i] * b[i];
res = res + pro;
// If both product and b[i] are negative, we must
// increase value of a[i] to minimize result.
if (pro < 0 && b[i] < 0)
temp = (a[i] + 2 * k) * b[i];
// If both product and a[i] are negative, we must
// decrease value of a[i] to minimize result.
else if (pro < 0 && a[i] < 0)
temp = (a[i] - 2 * k) * b[i];
// Similar to above two cases for positive product.
else if (pro > 0 && a[i] < 0)
temp = (a[i] + 2 * k) * b[i];
else if (pro > 0 && a[i] > 0)
temp = (a[i] - 2 * k) * b[i];
// Check if current difference becomes higher than
// the maximum difference so far.
int d = abs(pro - temp);
if (d > diff)
diff = d;
}
return res - diff;
}
// Driver function
int main()
{
int a[] = { 2, 3, 4, 5, 4 };
int b[] = { 3, 4, 2, 3, 2 };
int n = 5, k = 3;
cout << minproduct(a, b, n, k) << endl;
return 0;
}
// This code is contributed by Sania Kumari Gupta
C
// C program to find minimum sum of product
// of two arrays with k operations allowed on
// first array.
#include <stdio.h>
#include<stdlib.h>
// Function to find the minimum product
int minproduct(int a[], int b[], int n, int k)
{
int diff = 0, res = 0;
int temp;
for (int i = 0; i < n; i++) {
// Find product of current elements and update
// result.
int pro = a[i] * b[i];
res = res + pro;
// If both product and b[i] are negative, we must
// increase value of a[i] to minimize result.
if (pro < 0 && b[i] < 0)
temp = (a[i] + 2 * k) * b[i];
// If both product and a[i] are negative, we must
// decrease value of a[i] to minimize result.
else if (pro < 0 && a[i] < 0)
temp = (a[i] - 2 * k) * b[i];
// Similar to above two cases for positive product.
else if (pro > 0 && a[i] < 0)
temp = (a[i] + 2 * k) * b[i];
else if (pro > 0 && a[i] > 0)
temp = (a[i] - 2 * k) * b[i];
// Check if current difference becomes higher than
// the maximum difference so far.
int d = abs(pro - temp);
if (d > diff)
diff = d;
}
return res - diff;
}
// Driver function
int main()
{
int a[] = { 2, 3, 4, 5, 4 };
int b[] = { 3, 4, 2, 3, 2 };
int n = 5, k = 3;
printf("%d ",minproduct(a, b, n, k));
return 0;
}
// This code is contributed by Sania Kumari Gupta
Java
// Java program to find minimum sum of product of two arrays
// with k operations allowed on first array.
import java.math.*;
class GFG {
// Function to find the minimum product
static int minproduct(int a[], int b[], int n, int k)
{
int diff = 0, res = 0;
int temp = 0;
for (int i = 0; i < n; i++) {
// Find product of current elements and update
// result.
int pro = a[i] * b[i];
res = res + pro;
// If both product and b[i] are negative, we
// must increase value of a[i] to minimize
// result.
if (pro < 0 && b[i] < 0)
temp = (a[i] + 2 * k) * b[i];
// If both product and a[i] are negative, we
// must decrease value of a[i] to minimize
// result.
else if (pro < 0 && a[i] < 0)
temp = (a[i] - 2 * k) * b[i];
// Similar to above two cases for positive
// product.
else if (pro > 0 && a[i] < 0)
temp = (a[i] + 2 * k) * b[i];
else if (pro > 0 && a[i] > 0)
temp = (a[i] - 2 * k) * b[i];
// Check if current difference becomes higher
// than the maximum difference so far.
int d = Math.abs(pro - temp);
if (d > diff)
diff = d;
}
return res - diff;
}
// Driver function
public static void main(String[] args)
{
int a[] = { 2, 3, 4, 5, 4 };
int b[] = { 3, 4, 2, 3, 2 };
int n = 5, k = 3;
System.out.println(minproduct(a, b, n, k));
}
}
// This code is contributed by Sania Kumari Gupta
Python3
# Python program to find
# minimum sum of product
# of two arrays with k
# operations allowed on
# first array.
# Function to find the minimum product
def minproduct(a,b,n,k):
diff = 0
res = 0
for i in range(n):
# Find product of current
# elements and update result.
pro = a[i] * b[i]
res = res + pro
# If both product and
# b[i] are negative,
# we must increase value
# of a[i] to minimize result.
if (pro < 0 and b[i] < 0):
temp = (a[i] + 2 * k) * b[i]
# If both product and
# a[i] are negative,
# we must decrease value
# of a[i] to minimize result.
elif (pro < 0 and a[i] < 0):
temp = (a[i] - 2 * k) * b[i]
# Similar to above two cases
# for positive product.
elif (pro > 0 and a[i] < 0):
temp = (a[i] + 2 * k) * b[i]
elif (pro > 0 and a[i] > 0):
temp = (a[i] - 2 * k) * b[i]
# Check if current difference
# becomes higher
# than the maximum difference so far.
d = abs(pro - temp)
if (d > diff):
diff = d
return res - diff
# Driver function
a = [ 2, 3, 4, 5, 4 ]
b = [ 3, 4, 2, 3, 2 ]
n = 5
k = 3
print(minproduct(a, b, n, k))
# This code is contributed
# by Azkia Anam.
C#
// C# program to find minimum sum
// of product of two arrays with k
// operations allowed on first array.
using System;
class GFG {
// Function to find the minimum product
static int minproduct(int []a, int []b,
int n, int k)
{
int diff = 0, res = 0;
int temp = 0;
for (int i = 0; i < n; i++)
{
// Find product of current elements
// and update result.
int pro = a[i] * b[i];
res = res + pro;
// If both product and b[i] are
// negative, we must increase value
// of a[i] to minimize result.
if (pro < 0 && b[i] < 0)
temp = (a[i] + 2 * k) * b[i];
// If both product and a[i] are
// negative, we must decrease value
// of a[i] to minimize result.
else if (pro < 0 && a[i] < 0)
temp = (a[i] - 2 * k) * b[i];
// Similar to above two cases
// for positive product.
else if (pro > 0 && a[i] < 0)
temp = (a[i] + 2 * k) * b[i];
else if (pro > 0 && a[i] > 0)
temp = (a[i] - 2 * k) * b[i];
// Check if current difference
// becomes higher than the maximum
// difference so far.
int d = Math.Abs(pro - temp);
if (d > diff)
diff = d;
}
return res - diff;
}
// Driver function
public static void Main()
{
int []a = { 2, 3, 4, 5, 4 };
int []b = { 3, 4, 2, 3, 2 };
int n = 5, k = 3;
Console.WriteLine(minproduct(a, b, n, k));
}
}
// This code is contributed by vt_m.
JavaScript
<script>
// Javascript program to find minimum sum
// of product of two arrays with k
// operations allowed on first array.
// Function to find the minimum product
function minproduct(a, b, n, k)
{
let diff = 0, res = 0;
let temp = 0;
for (let i = 0; i < n; i++)
{
// Find product of current elements
// and update result.
let pro = a[i] * b[i];
res = res + pro;
// If both product and b[i] are
// negative, we must increase value
// of a[i] to minimize result.
if (pro < 0 && b[i] < 0)
temp = (a[i] + 2 * k) * b[i];
// If both product and a[i] are
// negative, we must decrease value
// of a[i] to minimize result.
else if (pro < 0 && a[i] < 0)
temp = (a[i] - 2 * k) * b[i];
// Similar to above two cases
// for positive product.
else if (pro > 0 && a[i] < 0)
temp = (a[i] + 2 * k) * b[i];
else if (pro > 0 && a[i] > 0)
temp = (a[i] - 2 * k) * b[i];
// Check if current difference
// becomes higher than the maximum
// difference so far.
let d = Math.abs(pro - temp);
if (d > diff)
diff = d;
}
return res - diff;
}
// Driver code
let a = [ 2, 3, 4, 5, 4 ];
let b = [ 3, 4, 2, 3, 2 ];
let n = 5, k = 3;
document.write(minproduct(a, b, n, k));
// This code is contributed by sanjoy_62.
</script>
PHP
<?php
// PHP program to find minimum sum of product
// of two arrays with k operations allowed on
// first array.
// Function to find the minimum product
function minproduct( $a, $b, $n, $k)
{
$diff = 0; $res = 0;
$temp;
for ( $i = 0; $i < $n; $i++) {
// Find product of current
// elements and update
// result.
$pro = $a[$i] * $b[$i];
$res = $res + $pro;
// If both product and b[i]
// are negative, we must
// increase value of a[i]
// to minimize result.
if ($pro < 0 and $b[$i] < 0)
$temp = ($a[$i] + 2 * $k) *
$b[$i];
// If both product and
// a[i] are negative,
// we must decrease value
// of a[i] to minimize
// result.
else if ($pro < 0 and $a[$i] < 0)
$temp = ($a[$i] - 2 * $k) * $b[$i];
// Similar to above two
// cases for positive
// product.
else if ($pro > 0 and $a[$i] < 0)
$temp = ($a[$i] + 2 * $k) * $b[$i];
else if ($pro > 0 and $a[$i] > 0)
$temp = ($a[$i] - 2 * $k) * $b[$i];
// Check if current difference becomes higher
// than the maximum difference so far.
$d = abs($pro - $temp);
if ($d > $diff)
$diff = $d;
}
return $res - $diff;
}
// Driver Code
$a = array(2, 3, 4, 5, 4 ,0);
$b =array(3, 4, 2, 3, 2);
$n = 5;
$k = 3;
echo minproduct($a, $b, $n, $k);
// This code is contributed by anuj_67.
?>
Output :
25
Time Complexity: O(n)
Auxiliary Space: O(1)
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem