C++ Online Compiler
Example: Longest Subarray Average K - Brute Force in C++
C
C++
C#
Java
Python
PHP
main.cpp
STDIN
Run
// Longest Subarray Average K - Brute Force #include <iostream> #include <vector> #include <numeric> // For std::accumulate (optional, can manually sum) #include <algorithm> // For std::max #include <iomanip> // For std::fixed, std::setprecision using namespace std; int main() { vector<int> nums = {1, 12, -5, -6, 50, 3}; double k = 4.0; int n = nums.size(); int maxLength = 0; // Step 1: Iterate through all possible starting points (i) for (int i = 0; i < n; ++i) { long long currentSum = 0; // Step 2: Iterate through all possible ending points (j) for the current start (i) for (int j = i; j < n; ++j) { currentSum += nums[j]; // Add current element to sum int currentLength = j - i + 1; double currentAverage = static_cast<double>(currentSum) / currentLength; // Step 3: Check if the current subarray's average is >= k if (currentAverage >= k) { // Step 4: Update maxLength if a longer valid subarray is found maxLength = max(maxLength, currentLength); } } } cout << "Array: "; for (int x : nums) { cout << x << " "; } cout << endl; cout << "Target average k: " << fixed << setprecision(2) << k << endl; cout << "Longest subarray length (Brute Force): " << maxLength << endl; return 0; }
Output
Clear
ADVERTISEMENTS