 <p>I have written a code according to my logic. It gives correct output for all the possible inputs came in my mind so have a look at it.</p> <pre><code>import java.util.Scanner; class Combination { public static void main(String args[]) { Scanner sc =new Scanner(System.in); System.out.println("Enter total number of fruit1:"); int fruit_1=sc.nextInt(); System.out.println("Enter total number of fruit2:"); int fruit_2=sc.nextInt(); System.out.println("Enter total number of fruits you want in combination:"); int total=sc.nextInt(); int max=0; int min=0; if(fruit_1&gt;fruit_2) { max=fruit_1; min=fruit_2; } else { max=fruit_2; min=fruit_1; } int ans=0; if(max&gt;total &amp;&amp; min&gt;total) ans=total+1; else if(max&gt;total &amp;&amp; min&lt;total) ans=min+1; else ans=fruit_1+fruit_2-total+1; if(ans&lt;0) //if A+B&lt;N but u didn't consider in the question System.out.println("Possible Combinations:0"); else System.out.println("Possible Combinations:"+ans); } } </code></pre> <p><strong>EDIT</strong>: Actually I tried to make algorithm and I have made an easier algorithm which will give <code>O(1)</code> Complexity.</p> <pre><code>Take Input A,B from user. Take Input N. Min=Minimum(A,B) Max=Maximum(A,B) If Max&gt;N &amp;&amp; Min&gt;N OP=N+1; else If Max&gt;N &amp;&amp; Min&lt;N OP=Min+1; else //Max&lt;N &amp;&amp; Min&lt;N OR Any other cases OP=A+B+1-N; </code></pre>