I am trying to solve a programming problem on a coding platform. When I execute it on my PC, it works perfectly, but when I submit the code on the coding platform, it throws a "Time Limit Exceeded" error. Can someone check my solution and help optimize it?
Given a number N, the program must print the pattern as described below.
Input Format:The first line contains the value of the N which represent the number N. Output Format:The pattern as described below in the Example.
> Input: 4
> Output:
4444444
4333334
4322234
4321234
4322234
4333334
4444444
My Approach
Print Upper rectangle and then print the lower rectangle.
The problem statement and my code can also be found here.
import java.util.Scanner;
public class Test004_3 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int N = sc.nextInt();
/* PRINT UPPER PART
4444444
4333334
4322234
4321234
*/
for(int i = N; i>(1); i--)
{
for(int j = N; j >i; j--)
System.out.print(j);
for(int j = 0; j<(i*2)-1; j++)
System.out.print(i);
for(int j = i+1; j<=N; j++)
System.out.print(j);
System.out.println("");
}
/*
PRINT LOWER PART
4322234
4333334
4444444
*/
for(int i = 1; i<=(N); i++)
{
for(int j = N; j>i; j--)
System.out.print(j);
for(int j = 0; j<(i*2)-1; j++)
System.out.print(i);
for(int j = i+1; j <=N; j++)
System.out.print(j);
System.out.println("");
}
}
}
2 ms
for input of4
and100 ms
for input of100
on my Macbook Pro, which as @RolandIllig said is pretty quick. \$\endgroup\$