Minimum operations to make Array sum at most S from given Array
Last Updated :
07 Jan, 2022
Given an array arr[], of size N and an integer S, the task is to find the minimum operations to make the sum of the array less than or equal to S. In each operation:
- Any element can be chosen and can be decremented by 1, or
- Can be replaced by any other element in the array.
Examples:
Input: arr[]= {1, 2, 1 ,3, 1 ,2, 1}, S= 8
Output: 2
Explanation: Initially sum of the array is 11.
Now decrease 1 at index 0 to 0 and Replace 3 by 0.
The sum becomes 7 < 8. So 2 operations.
Input: arr[] = {1,2,3,4}, S= 11
Output: 0
Explanation: Sum is already < =11 so 0 operations.
Approach: This problem can be solved using the greedy approach and suffix sum by sorting the array. Applying the 1st operation on the minimum element any number of times and then applying the 2nd operation on the suffixes by replacing it with the minimum element after the first operation gives the minimum operations.
First sort the array. Consider performing x operations of 1st type on the arr[0] and then performing the 2nd operation on the suffix of the array of length i. Also consider the sum for this suffix of length i is sufSum.
Sum of the modified array must be <=S
So, the difference to be subtracted from the sum must be (diff)>= sum - S.
If x operations of type 1 is done on minimum element and type 2 operations are done the suffix of the array from [i,n) the sum of the decreased array is
cost = x + s - (n-i) * (a[0] - x)
cost = (n-i+1)* x-(n-i)* a[0] +s
cost >= sum - S = diff
s - (n-i) * a[0] + (n-i+1) *x >= diff
so x >= (diff - s+(n-i)* a[0]) / (n-i+1)
The minimum value of x is x = ceil((diff -s+ (n-i)* a[0]) / (n-i+1))
So the total operations are x (type-1) + (n-i) type-2
Follow these steps to solve the above problems:
- Initialize a variable sum = 0 and the size of the array to N.
- Iterate through the vector and find the sum of the array.
- If sum < = S print 0 and return.
- Sort the vector and assign diff = sum-S.
- Initialize ops = sum-S which is the maximum possible operations.
- Initialize s =0 which stores the suffix sum of the vector.
- Now traverse from the end of the vector using for loop.
- Keep track of suffix sum in s variable.
- Initialize a dec variable which is the value to be decremented from the suffix of the array
- If s-dec is greater than or equal to diff there is no need to decrement arr[0] so assign x =0.
- Else find the value of x which is the value to be decremented in arr[0] and find the minimum operations.
- Print the minimum operations
Below is the implementation of the above approach:
C++
// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
// Function to divide and get the ceil value
int ceil_div(int a, int b)
{
return a / b + ((a ^ b) > 0 && a % b);
}
// Function to find the minimum cost
void minimum_cost(vector<int> arr, int S)
{
int sum = 0;
int n = arr.size();
// Find the sum of the array
for (int i = 0; i < arr.size(); i++) {
sum += arr[i];
}
// If sum <= S no operations required
if (sum <= S) {
cout << 0 << endl;
return;
}
// Sort the array
sort(arr.begin(), arr.end());
int diff = sum - S;
// Maximum it requires sum-S operations
// by decrementing
// the arr[0] by 1
int ops = sum - S;
// suffix sum
int s = 0;
int x;
for (int i = n - 1; i > 0; i--) {
s += arr[i];
// If replacing the last elements
// with doing the first operation
// x = 0 Decrementing the a[i] from
// the suffix [i,n-1]
int dec = (n - i) * arr[0];
if (s - dec >= diff) {
x = 0;
}
// Find how times the first element
// should be decremented by 1 and
// incremented by 1 which is x
else {
x = max(ceil_div((diff - s + dec),
(n - i + 1)), 0);
}
// First operation + second operation
if (x + n - i < ops) {
ops = x + n - i;
}
}
// Print the operations
cout << ops << endl;
}
// Driver code
int main()
{
// Initialize the array
vector<int> arr = { 1, 2, 1, 3, 1, 2, 1 };
int S = 8;
// Function call
minimum_cost(arr, S);
return 0;
}
Java
// Java program for the above approach
import java.util.Arrays;
class GFG {
// Function to divide and get the ceil value
static int ceil_div(int a, int b) {
int temp = 0;
if (((a ^ b) > 0) && ((a % b) > 0)) {
temp = 1;
}
return (a / b) + temp;
}
// Function to find the minimum cost
static void minimum_cost(int[] arr, int S) {
int sum = 0;
int n = arr.length;
// Find the sum of the array
for (int i = 0; i < arr.length; i++) {
sum += arr[i];
}
// If sum <= S no operations required
if (sum <= S) {
System.out.println(0);
return;
}
// Sort the array
Arrays.sort(arr);
int diff = sum - S;
// Maximum it requires sum-S operations
// by decrementing
// the arr[0] by 1
int ops = sum - S;
// suffix sum
int s = 0;
int x;
for (int i = n - 1; i > 0; i--) {
s += arr[i];
// If replacing the last elements
// with doing the first operation
// x = 0 Decrementing the a[i] from
// the suffix [i,n-1]
int dec = (n - i) * arr[0];
if (s - dec >= diff) {
x = 0;
}
// Find how times the first element
// should be decremented by 1 and
// incremented by 1 which is x
else {
x = Math.max(ceil_div((diff - s + dec),
(n - i + 1)), 0);
}
// First operation + second operation
if (x + n - i < ops) {
ops = x + n - i;
}
}
// Print the operations
System.out.println(ops);
}
// Driver code
public static void main(String args[])
{
// Initialize the array
int[] arr = { 1, 2, 1, 3, 1, 2, 1 };
int S = 8;
// Function call
minimum_cost(arr, S);
}
}
// This code is contributed by saurabh_jaiswal.
Python3
# Python 3 program for the above approach
# Function to divide and get the ceil value
def ceil_div(a, b):
return a // b + ((a ^ b) > 0 and a % b)
# Function to find the minimum cost
def minimum_cost(arr, S):
sum = 0
n = len(arr)
# Find the sum of the array
for i in range(len(arr)):
sum += arr[i]
# If sum <= S no operations required
if (sum <= S):
print(0)
return
# Sort the array
arr.sort()
diff = sum - S
# Maximum it requires sum-S operations
# by decrementing
# the arr[0] by 1
ops = sum - S
# suffix sum
s = 0
for i in range(n - 1, -1, -1):
s += arr[i]
# If replacing the last elements
# with doing the first operation
# x = 0 Decrementing the a[i] from
# the suffix [i,n-1]
dec = (n - i) * arr[0]
if (s - dec >= diff):
x = 0
# Find how times the first element
# should be decremented by 1 and
# incremented by 1 which is x
else:
x = max(ceil_div((diff - s + dec),
(n - i + 1)), 0)
# First operation + second operation
if (x + n - i < ops):
ops = x + n - i
# Print the operations
print(ops)
# Driver code
if __name__ == "__main__":
# Initialize the array
arr = [1, 2, 1, 3, 1, 2, 1]
S = 8
# Function call
minimum_cost(arr, S)
# This code is contributed by ukasp.
C#
// C# program for the above approach
using System;
class GFG
{
// Function to divide and get the ceil value
static int ceil_div(int a, int b) {
int temp = 0;
if (((a ^ b) > 0) && ((a % b) > 0)) {
temp = 1;
}
return (a / b) + temp;
}
// Function to find the minimum cost
static void minimum_cost(int[] arr, int S) {
int sum = 0;
int n = arr.Length;
// Find the sum of the array
for (int i = 0; i < arr.Length; i++) {
sum += arr[i];
}
// If sum <= S no operations required
if (sum <= S) {
Console.WriteLine(0);
return;
}
// Sort the array
Array.Sort(arr);
int diff = sum - S;
// Maximum it requires sum-S operations
// by decrementing
// the arr[0] by 1
int ops = sum - S;
// suffix sum
int s = 0;
int x;
for (int i = n - 1; i > 0; i--) {
s += arr[i];
// If replacing the last elements
// with doing the first operation
// x = 0 Decrementing the a[i] from
// the suffix [i,n-1]
int dec = (n - i) * arr[0];
if (s - dec >= diff) {
x = 0;
}
// Find how times the first element
// should be decremented by 1 and
// incremented by 1 which is x
else {
x = Math.Max(ceil_div((diff - s + dec),
(n - i + 1)), 0);
}
// First operation + second operation
if (x + n - i < ops) {
ops = x + n - i;
}
}
// Print the operations
Console.Write(ops);
}
// Driver code
public static void Main()
{
// Initialize the array
int[] arr = { 1, 2, 1, 3, 1, 2, 1 };
int S = 8;
// Function call
minimum_cost(arr, S);
}
}
// This code is contributed by Samim Hossain Mondal.
JavaScript
<script>
// JavaScript program for the above approach
// Function to divide and get the ceil value
const ceil_div = (a, b) => parseInt(a / b) + ((a ^ b) > 0 && a % b);
// Function to find the minimum cost
const minimum_cost = (arr, S) => {
let sum = 0;
let n = arr.length;
// Find the sum of the array
for (let i = 0; i < arr.length; i++) {
sum += arr[i];
}
// If sum <= S no operations required
if (sum <= S) {
document.write("0<br/>");
return;
}
// Sort the array
arr.sort();
let diff = sum - S;
// Maximum it requires sum-S operations
// by decrementing
// the arr[0] by 1
let ops = sum - S;
// suffix sum
let s = 0;
let x;
for (let i = n - 1; i > 0; i--) {
s += arr[i];
// If replacing the last elements
// with doing the first operation
// x = 0 Decrementing the a[i] from
// the suffix [i,n-1]
let dec = (n - i) * arr[0];
if (s - dec >= diff) {
x = 0;
}
// Find how times the first element
// should be decremented by 1 and
// incremented by 1 which is x
else {
x = Math.max(ceil_div((diff - s + dec),
(n - i + 1)), 0);
}
// First operation + second operation
if (x + n - i < ops) {
ops = x + n - i;
}
}
// Print the operations
document.write(`${ops}<br/>`);
}
// Driver code
// Initialize the array
let arr = [1, 2, 1, 3, 1, 2, 1];
let S = 8;
// Function call
minimum_cost(arr, S);
// This code is contributed by rakeshsahni
</script>
Time Complexity: O(N* logN)
Space Complexity: 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