Brute force is a method where we try all possible options and choose the best valid one. It is simple but can be slow, so we use it only when the search space is small enough.
How Do We Brute Force?
Common patterns:
- Nested loops
- When number of variables is small and each has small range.
- Bitmask enumeration
- For subsets: for each mask from to , check included elements.
- Permutations
- Use
next_permutationin C++ to try all orderings.
- Use
- Backtracking / recursion
- Build solutions step by step and explore all possibilities (optionally with pruning).
Example 1: Maximum Sum of a Subarray of Length
Given an array of integers and an integer , find the maximum sum of contiguous subarray of length .
Try every starting index from to , sum elements starting at , and keep the maximum.