Find the minimum possible sum that can be made by the digits of given String
Last Updated :
26 Feb, 2024
Given a string S of length N along with K, the task is to output the minimum sum of suffix after making the longest prefix of zeros that can be obtained by applying the given operation at most K times. Then you can apply the given operation on S:
- Choose an index let’s say i (1 <= i <= N)
- Do this for each digit of S[1, i]
- Replace the digit with the remainder after incrementing it by one and then dividing it by 10.
Examples:
Input: N = 3, K = 9, S = “380”
Output: 0
Explanation: The series of operations is performed as:
- First Operation: Choose i = 2, We will apply operation on S[1, 2], then:
- Initially, S[1] = 3 and S[2] = 8. During operation: S[1] = (S[1]+1)%10 and S[2] = (S[2]+1)%10, then S[1] and S[2] are 4,9 respectively. Updated S = “490”
- Second Operation: Choose again, i = 2, We will apply operation on S[1, 2], then:
- Initially, S[1] = 4 and S[2] = 9. During operation: S[1] = (S[1]+1)%10 and S[2] = (S[2]+1)%10, then S[1] and S[2] are 5,0 respectively. Updated S = “500”
- Next 5 operations: Choose, i = 1, We will apply operation on S[1, 1], then:
- Initially, S[1] = 5. During operation: S[1] = (S[1]+1)%10, then S[1] = 0. Updated S = “000”
So, the length longest prefix that can be made using a given operation is obtained by using 7 (at most K = 9) operations. No digit is remained in the suffix after making it of all zeros. So the minimum sum of suffixes will be 0.
Input: N = 5, K = 13, S = “78712”
Output: 3
Explanation: It can be verified that the longest suffix of length 3 will formed in exactly 13 operations. Then Suffix S[4, 5] = 12 will remain. Whose sum is 3. Therefore, output is 3.
Approach: To solve the problem follow the below idea:
The main crux of the problem is to maximize the length of the prefix formed by zero. So that the sum formed by remaining digits will be lower itself. This problem is based on the Greedy logic. Now, let us see the different approaches to solve the problem.
In this approach we will maximizing the length of a prefix with all zeros in at most K times. Which is based on greedy algorithm. Here are the steps:
- Greedy logic: We have to iterate over each character in the string from left to right. For each character, We need to calculate the minimum number of operations required to make it ‘0’. This is done by subtracting the character’s value from 10 and taking the modulus 10.
- Checking Possibility: If at any point, the required operations for a character exceed the remaining operations, then break out of the loop. Otherwise, increment a counter (representing the length of the prefix with all zeros) and updates the remaining operations.
- results: Finally, after iterating over all characters or until no more operations can be performed, count the sum of suffix remained after the longest prefix of zeros. Calculate the sum of digits in that suffix and print it.
This approach ensures that we find the maximum length in O(N) time complexity where N is the length of the string.
Steps were taken to solve the problem:
- Declare a variable let say Count, to calculate the length longest prefix of zeros.
- Run a loop for i = 0 to i < S.length() and follow below mentioned steps under the scope of loop:
- num = (int)(S.charAt(i) – ‘0’)
- diff = (10 – num) % 10
- If(K < diff)
- Count++
- K = ((K – diff) / 10) * 10 + diff
- Declare a variable let say Min_sum to count the minimum sum.
- Iterate over the suffix after the longest prefix of zeros and calculate the sum of digits into Min_sum
- Output Min_sum.
Code to implement the approach:
C++
#include <iostream>
#include <string>
using namespace std;
void Min_sum( int N, int K, string S) {
int count = 0;
for ( int i = 0; i < S.length(); i++) {
int num = static_cast < int >(S[i] - '0' );
int diff = (10 - num) % 10;
if (K < diff) {
break ;
}
count++;
K = ((K - diff) / 10) * 10 + diff;
}
int min_sum = 0;
for ( int i = count; i < S.length(); i++) {
min_sum += (S[i] - '0' );
}
cout << min_sum << endl;
}
int main() {
int N = 3;
int K = 9;
string S = "380" ;
Min_sum(N, K, S);
return 0;
}
|
Java
import java.util.*;
class GFG {
public static void main(String[] args)
{
int N = 3 ;
int K = 9 ;
String S = " 380 ";
Min_sum(N, K, S);
}
public static void Min_sum( int N, int K, String S)
{
int count = 0 ;
for ( int i = 0 ; i < S.length(); i++) {
int num = ( int )(S.charAt(i) - '0' );
int diff = ( 10 - num) % 10 ;
if (K < diff) {
break ;
}
count++;
K = ((K - diff) / 10 ) * 10 + diff;
}
int min_sum = 0 ;
for ( int i = count; i < S.length(); i++) {
min_sum += (S.charAt(i) - '0' );
}
System.out.println(min_sum);
}
}
|
Python3
def min_sum(N, K, S):
count = 0
for i in range ( len (S)):
num = int (S[i])
diff = ( 10 - num) % 10
if K < diff:
break
count + = 1
K = ((K - diff) / / 10 ) * 10 + diff
min_sum = 0
for i in range (count, len (S)):
min_sum + = int (S[i])
print (min_sum)
if __name__ = = "__main__" :
N = 3
K = 9
S = "380"
min_sum(N, K, S)
|
C#
using System;
class Program
{
static void MinSum( int N, int K, string S)
{
int count = 0;
for ( int i = 0; i < S.Length; i++)
{
int num = ( int )(S[i] - '0' );
int diff = (10 - num) % 10;
if (K < diff)
{
break ;
}
count++;
K = ((K - diff) / 10) * 10 + diff;
}
int minSum = 0;
for ( int i = count; i < S.Length; i++)
{
minSum += (S[i] - '0' );
}
Console.WriteLine(minSum);
}
static void Main()
{
int N = 3;
int K = 9;
string S = "380" ;
MinSum(N, K, S);
}
}
|
Javascript
function minSum(N, K, S) {
let count = 0;
for (let i = 0; i < S.length; i++) {
let num = parseInt(S[i]);
let diff = (10 - num) % 10;
if (K < diff) {
break ;
}
count++;
K = Math.floor((K - diff) / 10) * 10 + diff;
}
let minSum = 0;
for (let i = count; i < S.length; i++) {
minSum += parseInt(S[i]);
}
console.log(minSum);
}
let N = 3;
let K = 9;
let S = "380" ;
minSum(N, K, S);
|
Time Complexity: O(N)
Auxiliary Space: O(1)
- Binary Search: The approach performs a binary search on the range from 0 to N-1 (where N is the length of the string S). For each mid value, it checks if it’s possible to make all characters from index 0 to mid ‘0’ by using at most K operations or not.
- Checking Possibility: The possible() function checks if it’s possible to make all characters from index 0 to mid ‘0’. It does this by iterating from mid to 0 and for each character, it calculates the required operations to make it ‘0’. If at any point, the total required operations exceed K, it returns false. Otherwise, it returns true.
- Updating Answer: If it’s possible to make all characters from index 0 to mid ‘0’, then mid+1 is a potential answer and we try to find a bigger answer in the range from mid+1 to high. Otherwise, we try to find an answer in the range from low to mid-1.
- Results: Finally, after the binary search ends, We have the maximum length of a prefix with all zeros, after that we can get the minimum sum of suffix easily.
This approach ensures that we find the maximum length in O(N*log N) time complexity where N is the length of the string.
Steps were taken to solve the problem:
- Create two variables let say low and high and initialize them as 0 and N-1 respectively.
- Declare a variable let say Count to store the length of longest prefix of zeros.
- While (low <= high)
- mid = low + (high-low)/2
- If (possible (mid, S, K))
- Count = mid + 1
- low = mid + 1
- Else
- Declare a variable let say Min_sum to count the minimum sum.
- Iterate over the suffix after the longest prefix of zeros and calculate the sum of digits into Min_sum
- Output Min_sum.
Code to implement the approach:
C++
#include <iostream>
using namespace std;
bool possible( int mid, const string& s, int k) {
int op = 0, req = 0;
for ( int i = mid; i >= 0; i--) {
req = ((s[i] - '0' ) + op) % 10;
if (req != 0) {
op += (10 - req);
}
}
return op <= k;
}
void Min_sum( int N, int K, const string& S) {
int low = 0, high = N - 1;
int count = 0;
while (low <= high) {
int mid = (low + high) / 2;
if (possible(mid, S, K)) {
count = mid + 1;
low = mid + 1;
} else {
high = mid - 1;
}
}
int min_sum = 0;
for ( int i = count; i < N; i++) {
min_sum += (S[i] - '0' );
}
cout << min_sum << endl;
}
int main() {
int N = 5;
int K = 13;
string S = "78712" ;
Min_sum(N, K, S);
return 0;
}
|
Java
import java.util.*;
class GFG {
public static void main(String[] args)
{
int N = 5 ;
int K = 13 ;
String S = " 78712 ";
Min_sum(N, K, S);
}
public static void Min_sum( int N, int K, String S)
{
int low = 0 , high = N - 1 ;
int count = 0 ;
while (low <= high) {
int mid = (low + high) / 2 ;
if (possible(mid, S, K)) {
count = mid + 1 ;
low = mid + 1 ;
}
else {
high = mid - 1 ;
}
}
int min_sum = 0 ;
for ( int i = count; i < S.length(); i++) {
min_sum += (S.charAt(i) - '0' );
}
System.out.println(min_sum);
}
static boolean possible( int mid, String s, int k)
{
int op = 0 , req = 0 ;
for ( int i = mid; i >= 0 ; i--)
{
req = ((s.charAt(i) - '0' ) + op) % 10 ;
if (req != 0 )
op += ( 10 - req);
}
return op <= k;
}
}
|
Python3
def possible(mid, s, k):
op = 0
req = 0
for i in range (mid, - 1 , - 1 ):
req = (( ord (s[i]) - ord ( '0' )) + op) % 10
if req ! = 0 :
op + = ( 10 - req)
return op < = k
def min_sum(n, k, s):
low = 0
high = n - 1
count = 0
while low < = high:
mid = (low + high) / / 2
if possible(mid, s, k):
count = mid + 1
low = mid + 1
else :
high = mid - 1
min_sum = 0
for i in range (count, n):
min_sum + = int (s[i])
print (min_sum)
if __name__ = = "__main__" :
N = 5
K = 13
S = "78712"
min_sum(N, K, S)
|
C#
using System;
public class GFG {
static bool Possible( int mid, string s, int k)
{
int op = 0, req = 0;
for ( int i = mid; i >= 0; i--) {
req = ((s[i] - '0' ) + op) % 10;
if (req != 0) {
op += (10 - req);
}
}
return op <= k;
}
static void MinSum( int N, int K, string S)
{
int low = 0, high = N - 1;
int count = 0;
while (low <= high) {
int mid = (low + high) / 2;
if (Possible(mid, S, K)) {
count = mid + 1;
low = mid + 1;
}
else {
high = mid - 1;
}
}
int minSum = 0;
for ( int i = count; i < N; i++) {
minSum += (S[i] - '0' );
}
Console.WriteLine(minSum);
}
public static void Main()
{
int N = 5;
int K = 13;
string S = "78712" ;
MinSum(N, K, S);
}
}
|
Javascript
function possible(mid, s, k) {
let op = 0, req = 0;
for (let i = mid; i >= 0; i--) {
req = ((parseInt(s[i]) - 0) + op) % 10;
if (req !== 0) {
op += (10 - req);
}
}
return op <= k;
}
function Min_sum(N, K, S) {
let low = 0, high = N - 1;
let count = 0;
while (low <= high) {
let mid = Math.floor((low + high) / 2);
if (possible(mid, S, K)) {
count = mid + 1;
low = mid + 1;
} else {
high = mid - 1;
}
}
let min_sum = 0;
for (let i = count; i < N; i++) {
min_sum += (parseInt(S[i]) - 0);
}
console.log(min_sum);
}
function main() {
let N = 5;
let K = 13;
let S = "78712" ;
Min_sum(N, K, S);
}
main();
|
Time Complexity: O(N*logN)
Auxiliary space: O(1)
Share your thoughts in the comments
Please Login to comment...