for the first question… what if we traverse the array from both directions and output minimum of the two?
MINIMUM PLUSES:
I 've tried this approach but, it passed only 62% of test cases:)
class Solution {
public static int minimum_pluses(String A,String Y){
if(A.equals(Y))
return -1;
char ch[]=A.toCharArray();
int rev=0,check=0,counter=0;
int n=ch.length;
int minimum=Integer.MAX_VALUE;
for( int i=0; i<n; i++){
int no=(ch[i]-'0');
rev=rev*10+no;
check=rev;
counter=0;
for( int j=i+1; j<n; j++){
counter++;
if((check+(ch[j]-'0'))==Integer.parseInt(Y)){
minimum=Math.min(minimum,counter);
break;
}
check+=(ch[j]-'0');
}
}
return minimum==Integer.MAX_VALUE? -1:minimum;
}
public static void main(String []args){
Scanner scan = new Scanner(System.in);
String A;
A=scan.next();
int result=Integer.MAX_VALUE;
String s[]=A.split("=");
result = minimum_pluses(s[0],s[1]);
System.out.print(result);
}
}
`
Answer of the second one:
import java.util.*;
public class Main {
public static void main(String args[]) {
Scanner scn=new Scanner(System.in);
String x=scn.next();//L.H.S of the equation
int y=scn.nextInt();//R.H.S of the equation
int res=min(x,y);
if(res>=10000)
{
System.out.println(-1);
}
else
{
System.out.println(res);
}
}
public static int min(String str,int num) {
if(num<0)
{
return 10000;
}
if(Integer.parseInt(str)==num)
{
return 0;
}
if(str.length()==1)
{
if(Integer.parseInt(str)==num)
{
return 0;
}
else
{
return 10000;
}
}
int ans=10000;
for(int i=1;i<str.length();i++)
{
int n=Integer.parseInt(str.substring(0,i));
String sub=str.substring(i);
ans=Math.min(ans,min(sub,num-n)+1);
}
return ans;
}
}
For 1st problem, you can find max length subarray possible with sum as (totalSumOfArrayElements - X), then if found such subarray then answer will be (lengthOfArray - maxLenSatisfying).
Using 2 pointer algo you can find max length subarray satisying condition in O(n) time complexity.
"""2nd one Answer"""
def permute(s):
result = [[s]]
for i in range(1, len(s)):
first = [s[:i]]
rest = s[i:]
for p in permute(rest):
result.append(first + p)
return [[int(j) for j in i] for i in result]
def problem(s):
x,y=s.split("=")
data=permute(x)
newdata=[]
for i in range(1,len(x)+1,1):
for j in data:
if i==len(j):
newdata.append(j)
for i in newdata:
if sum(i)==int(y):
print(“str 1”,i)
return
print(“str -1”)
def check_constraint(s):
if (not (1<=len(s)<=10^3)):
print(-1)
elif (s.split("=")[0]==s.split("=")[1]):
print(1)
elif (not (len(s.split("=")[0])>=len(s.split("=")[1]))):
print(-1)
else:
problem(s)
A=input()
check_constraint(A)
Are hackwithinfy questions really hard like this every year?