for(int i = 0; i < n; i++) { ... }
O(n²), O(2ⁿ), O(n!)).
public class MaxInArray
{
public static void main(String[] args)
{
int[] arr = {5, 12, 3, 19, 7};
// Assume first element is max
int max = arr[0];
// Check every element
for(int i = 1; i < arr.length; i++)
{
if(arr[i] > max)
{
max = arr[i];
}
}
System.out.println("Maximum element is: " + max);
}
}
Maximum element is: 19
public class PairWithSum
{
public static void main(String[] args)
{
int[] arr = {2, 7, 4, 5, 1, 3};
int target = 6;
System.out.println("Pairs with given sum " + target + " are:");
// Brute force approach: check all pairs
for(int i = 0; i < arr.length; i++)
{
for(int j = i + 1; j < arr.length; j++)
{
if(arr[i] + arr[j] == target)
{
System.out.println(arr[i] + " + " + arr[j] + " = " + target);
}
}
}
}
}
2 + 4 = 6 5 + 1 = 6
public class NQueens
{
public static void main(String[] args)
{
int N = 4; // Size of chessboard
int[] board = new int[N]; // board[i] = column of queen in row i
solveNQueens(board, 0, N);
}
// Recursive function to place queens row by row
public static void solveNQueens(int[] board, int row, int N)
{
if(row == N)
{
printBoard(board, N); // All queens placed successfully
return;
}
// Try all columns in current row
for(int col = 0; col < N; col++)
{
if(isSafe(board, row, col))
{
board[row] = col; // Place queen
solveNQueens(board, row + 1, N); // Move to next row
}
}
}
// Check if placing queen at (row, col) is safe
public static boolean isSafe(int[] board, int row, int col)
{
for(int i = 0; i < row; i++)
{
// Same column or diagonal attack
if(board[i] == col || Math.abs(board[i] - col) == row - i)
{
return false;
}
}
return true;
}
// Print the board
public static void printBoard(int[] board, int N)
{
for(int i = 0; i < N; i++)
{
for(int j = 0; j < N; j++)
{
if(board[i] == j) System.out.print("Q ");
else System.out.print(". ");
}
System.out.println();
}
System.out.println();
}
}
. Q . . . . . Q Q . . . . . Q .
. . Q . Q . . . . . . Q . Q . .
Try below programs using Brute-Force Approach in Java:
Your feedback helps us grow! If there's anything we can fix or improve, please let us know.
We’re here to make our tutorials better based on your thoughts and suggestions.