rajdeepgupta20
BAN USER
@satveer: Yes, maintaining another stack is a solution. But we need to be careful about duplicate elements. If the current value is equal to the top of the " minimum stack" then also we need to push the element in both the stacks, i.e. the "main stack" and the "minimum stack".
Or may be we may store the count of the elements in the "minimum stack" with the elements. In that way, we may save space.
This is a simple recursive solution. You can optimize it by storing the solution to the sub-problems (dynamic programming).
#include<stdio.h>
void print_zero(int a[], int n, int indx, int sum, int r[], int r_indx)
{
int i,j;
for(i=indx; i<n; i++)
{
r[r_indx]=a[i];
if(sum+a[i]==0)
{
for(j=0; j<r_indx; j++)
printf("%d ",r[j]);
printf("%d\n",a[i]);
}
print_zero(a, n, i+1, sum+a[i], r, r_indx+1);
}
}
int main()
{
int a[]={1,-1,2,-2};
int n = sizeof(a)/sizeof(a[0]);
int r[n];
print_zero(a,n,0,0,r,0);
return 0;
}
Above code has a compilation error in the statement mid = (low+high)>>;1;
an extra semicolon is there. The rest is fine. The complexity of this code in O(logn). However if you want to return the exact square root then you need to define some error margin, say "e". In that case the complexity will be O(log(n/e)).
/*This code properly maintains overflow by returning the number of 1's in the answer */
int f(int num)
{
int a = 111;
int length=3;
while(1)
{
if(a%num == 0 ) return length;
a = a*10 + 1;
if(a>=num) a%=num;
length++;
}
}
int main()
{
int length = f(23);
int i;
for(i=1; i<=length; i++)
printf("1");
printf("\n");
return 0;
}
Miguel Oliveira : The problem statement has been updated. The continuous part was not mentioned before. It was only " subsequence "
- rajdeepgupta20 August 13, 2013