Minimize sum of Array formed using given relation between adjacent elements
Last Updated :
28 Apr, 2023
Given a binary string S of length N, consisting of 0's and 1's, the task is to find the minimum sum of the array of non-negative integers of length N+1 created by following the below conditions:
- If the ith number in the given binary string is 0, then the (i + 1)th number in the array must be less than the ith number.
- If the ith number in the given binary string is 1, then the (i + 1)th number in the array must be greater than the ith number.
Examples:
Input: N = 3, S = "100"
Output: 3
Explanation: We can create the array [0, 2, 1, 0].
So total sum will be 0 + 2 + 1 + 0 = 3.
Hence, resultant array follows the conditions, and ‘3’ is the minimum value we can achieve.
Input: N = 3, S = "101"
Output: 2
Explanation: We can create the array [0, 1, 0, 1].
So total sum will be 0 + 1 + 0 + 1 = 2.
Hence, resultant array follows the conditions, and ‘2’ is the minimum value we can achieve.
Approach: This problem can be solved by using greedy approach based on the following observation:
- Consider we have K consecutive 1, in this case, last value will be at least K, as array would look something like this [0, 1, 2, …, K - 1, K], this would give us a minimum sum.
- Same thing if we have K consecutive 0, in this case, array will look something like this [K, K - 1, ..., 2, 1, 0], hence our first value will be at least K.
- Thus the ith element of the answer array will be the maximum among consecutive 1's to its left and consecutive 0's to its right.
If we take a value greater than the maximum value, we will increase our sum, and hence the sum will not be minimum. If we take any less value than the maximum value, then one of the values in the array will become less than 0, which is a violation of the condition.
Follow the below steps to solve this problem:
- Construct two arrays of length N + 1 (say arr1[] and arr2[] )and fill all the values as ‘0’.
- Traverse from i = 0 to N - 1.
- If S[i] value is 1 set arr1[i+1] = arr1[i]+1.
- Traverse from i = N - 1 to 0.
- If S[i] value is 0 set arr2[i] = arr2[i+1]+1.
- Traverse in both the arrays from i = 0 to N:
- Add the maximum of arr1[i] and arr2[i] to the answer.
- Return the answer.
Below is the implementation of the above approach :
C++
// C++ code to implement the approach
#include <bits/stdc++.h>
using namespace std;
// Function to calculate the sum
long long minimumSum(string& s, int n)
{
vector<int> arr1(n + 1, 0), arr2(n + 1, 0);
// Finding maximum consecutive 1
// to the left, for each index
for (int i = 0; i < n; ++i) {
if (s[i] == '1') {
arr1[i + 1] = arr1[i] + 1;
}
}
// Finding maximum consecutive
// 0 to the right, for each index.
for (int i = n - 1; i >= 0; --i) {
if (s[i] == '0') {
arr2[i] = arr2[i + 1] + 1;
}
}
long long ans = 0;
// Loop to find the sum
for (int i = 0; i < n + 1; ++i) {
ans += max(arr1[i], arr2[i]);
}
return ans;
}
// Driver Code
int main()
{
int N = 3;
string S = "101";
// fzunction call
cout << minimumSum(S, N);
return 0;
}
Java
// Java code to implement the approach
import java.util.Arrays;
class GFG
{
// Function to calculate the sum
public static long minimumSum(String s, int n)
{
int arr1[] = new int[n + 1];
int arr2[] = new int[n + 1];
Arrays.fill(arr1, 0);
Arrays.fill(arr2, 0);
// Finding maximum consecutive 1
// to the left, for each index
for (int i = 0; i < n; ++i) {
if (s.charAt(i) == '1') {
arr1[i + 1] = arr1[i] + 1;
}
}
// Finding maximum consecutive
// 0 to the right, for each index.
for (int i = n - 1; i >= 0; --i) {
if (s.charAt(i) == '0') {
arr2[i] = arr2[i + 1] + 1;
}
}
long ans = 0;
// Loop to find the sum
for (int i = 0; i < n + 1; ++i) {
ans += Math.max(arr1[i], arr2[i]);
}
return ans;
}
// Driver code
public static void main(String[] args)
{
int N = 3;
String S = "101";
// function call
System.out.println(minimumSum(S, N));
}
}
// This code is contributed by phasing17
Python3
# Python3 code for the above approach
# Function to calculate the sum
def minimumSum(s, n):
arr1 = [0] * (n + 1)
arr2 = [0] * (n + 1)
# Finding maximum consecutive 1
# to the left, for each index
for i in range(n):
if s[i] == "1":
arr1[i + 1] = arr1[i] + 1
# Finding maximum consecutive
# 0 to the right, for each index
for i in range(n - 1, -1, -1):
if s[i] == "0":
arr2[i] = arr2[i + 1] + 1
ans = 0
# Loop to find the sum
for i in range(n + 1):
ans += max(arr1[i], arr2[i])
return ans
# Driver code
N = 3
S = "101"
print(minimumSum(S, N))
# This code is contributed by phasing17
C#
// C# program to implement
// the above approach
using System;
class GFG
{
// Function to calculate the sum
public static long minimumSum(string s, int n)
{
int[] arr1 = new int[n + 1];
int[] arr2 = new int[n + 1];
for (int i = 0; i < n+1; i++) {
arr1[i] = 0;
}
for (int i = 0; i < n+1; i++) {
arr2[i] = 0;
}
// Finding maximum consecutive 1
// to the left, for each index
for (int i = 0; i < n; ++i) {
if (s[i] == '1') {
arr1[i + 1] = arr1[i] + 1;
}
}
// Finding maximum consecutive
// 0 to the right, for each index.
for (int i = n - 1; i >= 0; --i) {
if (s[i] == '0') {
arr2[i] = arr2[i + 1] + 1;
}
}
long ans = 0;
// Loop to find the sum
for (int i = 0; i < n + 1; ++i) {
ans += Math.Max(arr1[i], arr2[i]);
}
return ans;
}
// Driver Code
public static void Main()
{
int N = 3;
string S = "101";
// function call
Console.Write(minimumSum(S, N));
}
}
// This code is contributed by code_hunt.
JavaScript
<script>
// JavaScript code for the above approach
// Function to calculate the sum
function minimumSum(s, n) {
let arr1 = new Array(n + 1).fill(0), arr2 = new Array(n + 1).fill(0);
// Finding maximum consecutive 1
// to the left, for each index
for (let i = 0; i < n; ++i) {
if (s[i] == '1') {
arr1[i + 1] = arr1[i] + 1;
}
}
// Finding maximum consecutive
// 0 to the right, for each index.
for (let i = n - 1; i >= 0; --i) {
if (s[i] == '0') {
arr2[i] = arr2[i + 1] + 1;
}
}
let ans = 0;
// Loop to find the sum
for (let i = 0; i < n + 1; ++i) {
ans += Math.max(arr1[i], arr2[i]);
}
return ans;
}
// Driver Code
let N = 3;
let S = "101";
// fzunction call
document.write(minimumSum(S, N));
// This code is contributed by Potta Lokesh
</script>
Time Complexity: O(N)
Auxiliary Space O(N)
Another Approach:
- Initialize an array of length N+1 (say arr) with all elements set to 0.
- Traverse from i = 0 to N – 1.
(a) If S[i] value is 1, set arr[i+1] = arr[i]+1.
(b) If S[i] value is 0, set arr[i+1] = 0. - Traverse from i = N – 1 to 0.
(a) If S[i] value is 0, set arr[i] = max(arr[i], arr[i+1]+1). - Traverse in the array arr from i = 0 to N:
(a) Add the arr[i] value to the answer. - Return the answer.
C++
// C++ code to implement the approach
#include <bits/stdc++.h>
using namespace std;
// Function to calculate the sum
long long minimumSum(string& s, int n)
{
vector<int> arr(n + 1, 0);
// Finding maximum consecutive 1
// to the left, for each index
for (int i = 0; i < n; ++i) {
if (s[i] == '1') {
arr[i + 1] = arr[i] + 1;
}
}
// Finding maximum consecutive
// 0 to the right, for each index.
for (int i = n - 1; i >= 0; --i) {
if (s[i] == '0') {
arr[i] = max(arr[i], arr[i + 1] + 1);
}
}
long long ans = 0;
// Loop to find the sum
for (int i = 0; i < n + 1; ++i) {
ans += arr[i];
}
return ans;
}
// Driver Code
int main()
{
int N = 3;
string S = "101";
// fzunction call
cout << minimumSum(S, N);
return 0;
}
Java
import java.util.*;
public class Main {
// Function to calculate the sum
static long minimumSum(String s, int n) {
List<Integer> arr = new ArrayList<>(Collections.nCopies(n + 1, 0));
// Finding maximum consecutive 1
// to the left, for each index
for (int i = 0; i < n; ++i) {
if (s.charAt(i) == '1') {
arr.set(i + 1, arr.get(i) + 1);
}
}
// Finding maximum consecutive
// 0 to the right, for each index.
for (int i = n - 1; i >= 0; --i) {
if (s.charAt(i) == '0') {
arr.set(i, Math.max(arr.get(i), arr.get(i + 1) + 1));
}
}
long ans = 0;
// Loop to find the sum
for (int i = 0; i < n + 1; ++i) {
ans += arr.get(i);
}
return ans;
}
// Driver Code
public static void main(String[] args) {
int N = 3;
String S = "101";
// function call
System.out.println(minimumSum(S, N));
}
}
// This code is contributed by Akash Jha
Python3
# Python3 code to implement the approach
# Function to calculate the sum
def minimumSum(s, n):
arr = [0] * (n + 1)
# Finding maximum consecutive 1
# to the left, for each index
for i in range(n):
if s[i] == '1':
arr[i + 1] = arr[i] + 1
# Finding maximum consecutive
# 0 to the right, for each index.
for i in range(n - 1, -1, -1):
if s[i] == '0':
arr[i] = max(arr[i], arr[i + 1] + 1)
ans = 0
# Loop to find the sum
for i in range(n + 1):
ans += arr[i]
return ans
# Driver Code
N = 3
S = "101"
# Function call
print(minimumSum(S, N))
C#
// C# code to implement the approach
using System;
using System.Collections.Generic;
using System.Linq;
public class GFG
{
// Function to calculate the sum
public static long MinimumSum(string s, int n)
{
List<int> arr = new List<int>(n + 1);
for (int i = 0; i < n + 1; i++) {
arr.Add(0);
}
// Finding maximum consecutive 1
// to the left, for each index
for (int i = 0; i < n; i++) {
if (s[i] == '1') {
arr[i + 1] = arr[i] + 1;
}
}
// Finding maximum consecutive
// 0 to the right, for each index.
for (int i = n - 1; i >= 0; i--) {
if (s[i] == '0') {
arr[i] = Math.Max(arr[i], arr[i + 1] + 1);
}
}
long ans = 0;
// Loop to find the sum
for (int i = 0; i < n + 1; i++) {
ans += arr[i];
}
return ans;
}
// Driver Code
public static void Main()
{
int N = 3;
string S = "101";
// Function call
Console.Write(MinimumSum(S, N));
}
}
// This code is contributed by Akash Jha
JavaScript
// Function to calculate the sum
function minimumSum(s, n) {
let arr = new Array(n + 1).fill(0);
// Finding maximum consecutive 1
// to the left, for each index
for (let i = 0; i < n; ++i) {
if (s[i] == '1') {
arr[i + 1] = arr[i] + 1;
}
}
// Finding maximum consecutive
// 0 to the right, for each index.
for (let i = n - 1; i >= 0; --i) {
if (s[i] == '0') {
arr[i] = Math.max(arr[i], arr[i + 1] + 1);
}
}
let ans = 0;
// Loop to find the sum
for (let i = 0; i < n + 1; ++i) {
ans += arr[i];
}
return ans;
}
// Driver Code
let N = 3;
let S = "101";
// Function call
console.log(minimumSum(S, N));
Time Complexity: O(n)
Auxiliary Space: O(1)
Similar Reads
DSA Tutorial - Learn Data Structures and Algorithms
DSA (Data Structures and Algorithms) is the study of organizing data efficiently using data structures like arrays, stacks, and trees, paired with step-by-step procedures (or algorithms) to solve problems effectively. Data structures manage how data is stored and accessed, while algorithms focus on
7 min read
Quick Sort
QuickSort is a sorting algorithm based on the Divide and Conquer that picks an element as a pivot and partitions the given array around the picked pivot by placing the pivot in its correct position in the sorted array. It works on the principle of divide and conquer, breaking down the problem into s
12 min read
Merge Sort - Data Structure and Algorithms Tutorials
Merge sort is a popular sorting algorithm known for its efficiency and stability. It follows the divide-and-conquer approach. It works by recursively dividing the input array into two halves, recursively sorting the two halves and finally merging them back together to obtain the sorted array. Merge
14 min read
Bubble Sort Algorithm
Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order. This algorithm is not suitable for large data sets as its average and worst-case time complexity are quite high.We sort the array using multiple passes. After the fir
8 min read
Breadth First Search or BFS for a Graph
Given a undirected graph represented by an adjacency list adj, where each adj[i] represents the list of vertices connected to vertex i. Perform a Breadth First Search (BFS) traversal starting from vertex 0, visiting vertices from left to right according to the adjacency list, and return a list conta
15+ min read
Data Structures Tutorial
Data structures are the fundamental building blocks of computer programming. They define how data is organized, stored, and manipulated within a program. Understanding data structures is very important for developing efficient and effective algorithms. What is Data Structure?A data structure is a st
2 min read
Binary Search Algorithm - Iterative and Recursive Implementation
Binary Search Algorithm is a searching algorithm used in a sorted array by repeatedly dividing the search interval in half. The idea of binary search is to use the information that the array is sorted and reduce the time complexity to O(log N). Binary Search AlgorithmConditions to apply Binary Searc
15 min read
Insertion Sort Algorithm
Insertion sort is a simple sorting algorithm that works by iteratively inserting each element of an unsorted list into its correct position in a sorted portion of the list. It is like sorting playing cards in your hands. You split the cards into two groups: the sorted cards and the unsorted cards. T
9 min read
Dijkstra's Algorithm to find Shortest Paths from a Source to all
Given a weighted undirected graph represented as an edge list and a source vertex src, find the shortest path distances from the source vertex to all other vertices in the graph. The graph contains V vertices, numbered from 0 to V - 1.Note: The given graph does not contain any negative edge. Example
12 min read
Selection Sort
Selection Sort is a comparison-based sorting algorithm. It sorts an array by repeatedly selecting the smallest (or largest) element from the unsorted portion and swapping it with the first unsorted element. This process continues until the entire array is sorted.First we find the smallest element an
8 min read