Find the most combinations of two numbers that equal third or get close to it My task is to find how many different "tasks" can be done if I have two types of tasks that take specific time and time to complete all of them. I have to find the most tasks that can be done so that the gap between the time and sum of tasks is minimal. For example consider this input:

3 5 55


And output(2x5 + 15x3):

17


Or:

Input: 886 340 6177, Output: 10


Also:

Input: 3 5 54, Output: 18


My code is this:

 import java.util.Scanner;
 public class Protsessor {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int m = in.nextInt(); //Time of first task
        int n = in.nextInt(); //Time of second task
        int t = in.nextInt(); //Time available

        int tmpgap;
        int gap = t;
        int tasks = 0;
        int t1  = t;

        if( m &lt;= 0|| n &lt;= 0) { //If input is 0 or less
            System.out.println(0);
            System.exit(0);
        }
        if(m &gt; n) { //I rearrange my input as it doesn't work when m is bigger then n
            int tmp = m;
            m = n;
            n = tmp;
        }
        for (int i = 0; i &lt; (t/m+1); i++) {
            int tmptasks = 0;
            t1 -= i*m;
            tmptasks += i;
            for (int j = 0; j &lt; (t/n+1) &amp;&amp; t1 &gt;= n; j++) {
                t1 -= n;
                tmptasks++;
            }
            tmpgap = t1;
            if(tmpgap &lt;= gap){
                gap = tmpgap;
                tasks = tmptasks;
            }
            t1 = t;

        }
        System.out.println(tasks);
    }
}


As my code is quite messy, how can I optimize/improve it using dynamic programming?

NOTE: This was a task in competetive programming lesson, I already submitted this code(passed).
Have you simply tried to split code into smaller functions?

int t = in.nextInt(); //Time available


How about simply naming it timeAvailable instead of t ?

if(m &gt; n) { //I rearrange my input as it doesn't work when m is bigger then n
    int tmp = m;
    m = n;
    n = tmp;
}


Common pattern is something like:

int calculate(int m, int n, int t) {
    if (m &gt; n) {
        return calculate(n, m, t);
    }
    ...
}


Try to declare variables in smallest possible scope - int tmpgap; should be inside the for-loop. The inner for-loop might be replaced by division + Math.floor().