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.
Common patterns:
next_permutation in C++ to try all orderings.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.
#include <bits/stdc++.h>
using namespace std;
int main() {
int N, K;
cin >> N >> K;
vector<int> a(N);
for (int i = 0; i < N; i++) {
cin >> a[i];
}
long long best = LLONG_MIN;
// Brute force: try all subarrays of length K
for (int i = 0; i + K <= N; i++) {
long long sum = 0;
for (int j = i; j < i + K; j++) {
sum += a[j];
}
best = max(best, sum);
}
cout << best << endl;
return 0;
}