Maximum and Minimum Values of an Algebraic Expression
Last Updated :
03 Mar, 2023
Given an algebraic expression of the form (x1 + x2 + x3 + . . . + xn) * (y1 + y2 + . . . + ym) and (n + m) integers. Find the maximum and minimum value of the expression using the given integers.
Constraint :
n <= 50
m <= 50
-50 <= x1, x2, .. xn <= 50
Examples :
Input : n = 2, m = 2
arr[] = {1, 2, 3, 4}
Output : Maximum : 25
Minimum : 21
The expression is (x1 + x2) * (y1 + y2) and
the given integers are 1, 2, 3 and 4. Then
maximum value is (1 + 4) * (2 + 3) = 25
whereas minimum value is (4 + 3) * (2 + 1)
= 21.
Input : n = 3, m = 1
arr[] = {1, 2, 3, 4}
Output : Maximum : 24
Minimum : 9
A simple solution is to consider all possible combinations of n numbers and remaining m numbers and calculating their values, from which maximum value and minimum value can be derived.
Below is an efficient solution.
The idea is based on limited values of n, m, x1, x2, .. y1, y2, .. Let suppose S be the sum of all the (n + m) numbers in the expression and X be the sum of the n numbers on the left of expression. Obviously, the sum of the m numbers on the right of expression will be represented as (S - X). There can be many possible values of X from the given (n + m) numbers and hence the problem gets reduced to simply iterate through all values of X and keeping track of the minimum and maximum value of X * (S - X).
Now, the problem is equivalent to finding all possible values of X. Since the given numbers are in the range of -50 to 50 and the maximum value of (n + m) is 100, X will lie in between -2500 and 2500 which results into overall 5000 values of X. We will use dynamic programming approach to solve this problem. Consider a dp[i][j] array which can value either 1 or 0, where 1 means X can be equal to j by choosing i numbers from the (n + m) numbers and 0 otherwise. Then for each number k, if dp[i][j] is 1 then dp[i + 1][j + k] is also 1 where k belongs to given (n + m) numbers. Thus, by iterating through all k, we can determine whether a value of X is reachable by choosing a total of n numbers
Steps to solve the problem:
1. Initialize a variable "sum" to 0.
2. Traverse the array arr[] and add each element to sum.
*Shift each element by 50 so that all integers become positive.
3. Initialize a 2D array "dp" of size (n+1)x(MAX*MAX+1) to false.
4. Set dp[0][0] to true.
5. Traverse the array arr[].
*Set k to the minimum value between n and i+1.
*Traverse the dp array for all j from 0 to MAX*MAX+1.
*If dp[k-1][j] is true, set dp[k][j+arr[i]] to true.
6. Initialize two variables, "max_value" and "min_value" to -infinity and +infinity respectively.
7. Traverse the dp array for all i from 0 to MAXMAX+1.
*If dp[n][i] is true, do the following:
*Compute the actual sum "temp" by subtracting 50n from i.
*Compute the product "temp * (sum - temp)" and update the values of max_value and min_value.
8. Print the values of max_value and min_value.
Below is the implementation of the above approach.
C++
// CPP program to find the maximum
// and minimum values of an Algebraic
// expression of given form
#include <bits/stdc++.h>
using namespace std;
#define INF 1e9
#define MAX 50
int minMaxValues(int arr[], int n, int m)
{
// Finding sum of array elements
int sum = 0;
for (int i = 0; i < (n + m); i++) {
sum += arr[i];
// shifting the integers by 50
// so that they become positive
arr[i] += 50;
}
// dp[i][j] represents true if sum
// j can be reachable by choosing
// i numbers
bool dp[MAX+1][MAX * MAX + 1];
// initialize the dp array to 01
memset(dp, 0, sizeof(dp));
dp[0][0] = 1;
// if dp[i][j] is true, that means
// it is possible to select i numbers
// from (n + m) numbers to sum upto j
for (int i = 0; i < (n + m); i++) {
// k can be at max n because the
// left expression has n numbers
for (int k = min(n, i + 1); k >= 1; k--) {
for (int j = 0; j < MAX * MAX + 1; j++) {
if (dp[k - 1][j])
dp[k][j + arr[i]] = 1;
}
}
}
int max_value = -INF, min_value = INF;
for (int i = 0; i < MAX * MAX + 1; i++) {
// checking if a particular sum
// can be reachable by choosing
// n numbers
if (dp[n][i]) {
// getting the actual sum as
// we shifted the numbers by
/// 50 to avoid negative indexing
// in array
int temp = i - 50 * n;
max_value = max(max_value, temp * (sum - temp));
min_value = min(min_value, temp * (sum - temp));
}
}
cout << "Maximum Value: " << max_value
<< "\n"
<< "Minimum Value: "
<< min_value << endl;
}
// Driver Code
int main()
{
int n = 2, m = 2;
int arr[] = { 1, 2, 3, 4 };
minMaxValues(arr, n, m);
return 0;
}
Java
// Java program to find the maximum
// and minimum values of an Algebraic
// expression of given form
import java.io.*;
import java.lang.*;
public class GFG {
static double INF = 1e9;
static int MAX = 50;
static void minMaxValues(int []arr,
int n, int m)
{
// Finding sum of array elements
int sum = 0;
for (int i = 0; i < (n + m); i++)
{
sum += arr[i];
// shifting the integers by 50
// so that they become positive
arr[i] += 50;
}
// dp[i][j] represents true if sum
// j can be reachable by choosing
// i numbers
boolean dp[][] =
new boolean[MAX+1][MAX * MAX + 1];
dp[0][0] = true;
// if dp[i][j] is true, that means
// it is possible to select i numbers
// from (n + m) numbers to sum upto j
for (int i = 0; i < (n + m); i++) {
// k can be at max n because the
// left expression has n numbers
for (int k = Math.min(n, i + 1); k >= 1; k--)
{
for (int j = 0; j < MAX * MAX + 1; j++)
{
if (dp[k - 1][j])
dp[k][j + arr[i]] = true;
}
}
}
double max_value = -1 * INF, min_value = INF;
for (int i = 0; i < MAX * MAX + 1; i++)
{
// checking if a particular sum
// can be reachable by choosing
// n numbers
if (dp[n][i]) {
// getting the actual sum as
// we shifted the numbers by
/// 50 to avoid negative indexing
// in array
int temp = i - 50 * n;
max_value = Math.max(max_value, temp *
(sum - temp));
min_value = Math.min(min_value, temp *
(sum - temp));
}
}
System.out.print("Maximum Value: " +
(int)max_value + "\n" +
"Minimum Value: " + (int)min_value + "\n");
}
// Driver Code
public static void main(String args[])
{
int n = 2, m = 2;
int []arr = { 1, 2, 3, 4 };
minMaxValues(arr, n, m);
}
}
// This code is contributed by Manish Shaw
// (manishshaw1)
Python3
# Python3 program to find the
# maximum and minimum values
# of an Algebraic expression
# of given form
def minMaxValues(arr, n, m) :
# Finding sum of
# array elements
sum = 0
INF = 1000000000
MAX = 50
for i in range(0, (n + m)) :
sum += arr[i]
# shifting the integers by 50
# so that they become positive
arr[i] += 50
# dp[i][j] represents true
# if sum j can be reachable
# by choosing i numbers
dp = [[0 for x in range(MAX * MAX + 1)]
for y in range( MAX + 1)]
dp[0][0] = 1
# if dp[i][j] is true, that
# means it is possible to
# select i numbers from (n + m)
# numbers to sum upto j
for i in range(0, (n + m)) :
# k can be at max n because the
# left expression has n numbers
for k in range(min(n, i + 1), 0, -1) :
for j in range(0, MAX * MAX + 1) :
if (dp[k - 1][j]) :
dp[k][j + arr[i]] = 1
max_value = -1 * INF
min_value = INF
for i in range(0, MAX * MAX + 1) :
# checking if a particular
# sum can be reachable by
# choosing n numbers
if (dp[n][i]) :
# getting the actual sum
# as we shifted the numbers
# by 50 to avoid negative
# indexing in array
temp = i - 50 * n
max_value = max(max_value,
temp * (sum - temp))
min_value = min(min_value,
temp * (sum - temp))
print ("Maximum Value: {}\nMinimum Value: {}"
.format(max_value, min_value))
# Driver Code
n = 2
m = 2
arr = [ 1, 2, 3, 4 ]
minMaxValues(arr, n, m)
# This code is contributed by
# Manish Shaw(manishshaw1)
C#
// C# program to find the maximum
// and minimum values of an Algebraic
// expression of given form
using System;
using System.Collections.Generic;
class GFG {
static double INF = 1e9;
static int MAX = 50;
static void minMaxValues(int []arr, int n, int m)
{
// Finding sum of array elements
int sum = 0;
for (int i = 0; i < (n + m); i++)
{
sum += arr[i];
// shifting the integers by 50
// so that they become positive
arr[i] += 50;
}
// dp[i][j] represents true if sum
// j can be reachable by choosing
// i numbers
bool[,] dp = new bool[MAX+1, MAX * MAX + 1];
dp[0,0] = true;
// if dp[i][j] is true, that means
// it is possible to select i numbers
// from (n + m) numbers to sum upto j
for (int i = 0; i < (n + m); i++) {
// k can be at max n because the
// left expression has n numbers
for (int k = Math.Min(n, i + 1); k >= 1; k--)
{
for (int j = 0; j < MAX * MAX + 1; j++)
{
if (dp[k - 1,j])
dp[k,j + arr[i]] = true;
}
}
}
double max_value = -1 * INF, min_value = INF;
for (int i = 0; i < MAX * MAX + 1; i++)
{
// checking if a particular sum
// can be reachable by choosing
// n numbers
if (dp[n,i]) {
// getting the actual sum as
// we shifted the numbers by
/// 50 to avoid negative indexing
// in array
int temp = i - 50 * n;
max_value = Math.Max(max_value, temp *
(sum - temp));
min_value = Math.Min(min_value, temp *
(sum - temp));
}
}
Console.WriteLine("Maximum Value: " + max_value
+ "\n" + "Minimum Value: " + min_value + "\n");
}
// Driver Code
public static void Main()
{
int n = 2, m = 2;
int []arr = { 1, 2, 3, 4 };
minMaxValues(arr, n, m);
}
}
// This code is contributed by Manish Shaw
// (manishshaw1)
PHP
<?php
// PHP program to find the
// maximum and minimum values
// of an Algebraic expression
// of given form
function minMaxValues($arr, $n, $m)
{
// Finding sum of
// array elements
$sum = 0;
$INF = 1000000000;
$MAX = 50;
for ($i = 0; $i < ($n + $m); $i++)
{
$sum += $arr[$i];
// shifting the integers by 50
// so that they become positive
$arr[$i] += 50;
}
// dp[i][j] represents true
// if sum j can be reachable
// by choosing i numbers
$dp = array();
// new bool[MAX+1, MAX * MAX + 1];
for($i = 0; $i < $MAX + 1; $i++)
{
for($j = 0; $j < $MAX * $MAX + 1; $j++)
$dp[$i][$j] = 0;
}
$dp[0][0] = 1;
// if dp[i][j] is true, that
// means it is possible to
// select i numbers from (n + m)
// numbers to sum upto j
for ($i = 0; $i < ($n + $m); $i++)
{
// k can be at max n because the
// left expression has n numbers
for ($k = min($n, $i + 1);
$k >= 1; $k--)
{
for ($j = 0; $j < $MAX *
$MAX + 1; $j++)
{
if ($dp[$k - 1][$j])
$dp[$k][$j + $arr[$i]] = 1;
}
}
}
$max_value = -1 * $INF;
$min_value = $INF;
for ($i = 0; $i < $MAX * $MAX + 1; $i++)
{
// checking if a particular
// sum can be reachable by
// choosing n numbers
if ($dp[$n][$i])
{
// getting the actual sum
// as we shifted the numbers
// by 50 to avoid negative
// indexing in array
$temp = $i - 50 * $n;
$max_value = max($max_value, $temp *
($sum - $temp));
$min_value = min($min_value, $temp *
($sum - $temp));
}
}
echo ("Maximum Value: ". $max_value. "\n".
"Minimum Value: ". $min_value. "\n");
}
// Driver Code
$n = 2;
$m = 2;
$arr = [ 1, 2, 3, 4 ];
minMaxValues($arr, $n, $m);
// This code is contributed by
// Manish Shaw(manishshaw1)
?>
JavaScript
<script>
// Javascript program to find the maximum
// and minimum values of an Algebraic
// expression of given form
var INF = 1000000000
var MAX = 50
function minMaxValues(arr, n, m)
{
// Finding sum of array elements
var sum = 0;
for (var i = 0; i < (n + m); i++) {
sum += arr[i];
// shifting the integers by 50
// so that they become positive
arr[i] += 50;
}
// dp[i][j] represents true if sum
// j can be reachable by choosing
// i numbers
var dp = Array.from(Array(MAX+1), ()=> Array(MAX*MAX + 1).fill(0));
dp[0][0] = 1;
// if dp[i][j] is true, that means
// it is possible to select i numbers
// from (n + m) numbers to sum upto j
for (var i = 0; i < (n + m); i++) {
// k can be at max n because the
// left expression has n numbers
for (var k = Math.min(n, i + 1); k >= 1; k--) {
for (var j = 0; j < MAX * MAX + 1; j++) {
if (dp[k - 1][j])
dp[k][j + arr[i]] = 1;
}
}
}
var max_value = -INF, min_value = INF;
for (var i = 0; i < MAX * MAX + 1; i++) {
// checking if a particular sum
// can be reachable by choosing
// n numbers
if (dp[n][i]) {
// getting the actual sum as
// we shifted the numbers by
/// 50 to avoid negative indexing
// in array
var temp = i - 50 * n;
max_value = Math.max(max_value, temp * (sum - temp));
min_value = Math.min(min_value, temp * (sum - temp));
}
}
document.write( "Maximum Value: " + max_value
+ "<br>"
+ "Minimum Value: "
+ min_value );
}
// Driver Code
var n = 2, m = 2;
var arr =[1, 2, 3, 4];
minMaxValues(arr, n, m);
</script>
Output : Maximum Value: 25
Minimum Value: 21
Time Complexity: O(MAX * MAX * (n+m)2).
Auxiliary Space: O(MAX3)
This approach will have a runtime complexity of O(MAX * MAX * (n+m)2).
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