C Online Compiler
Example: Maximum Product Subarray (Brute Force) in C
C
C++
C#
Java
Python
PHP
main.c
STDIN
Run
// Maximum Product Subarray (Brute Force) #include
#include
// For INT_MIN int maxProductBruteForce(int nums[], int n) { if (n == 0) { return 0; // Or handle as an error, depending on requirements } int max_product = INT_MIN; // Initialize with the smallest possible integer value // Step 1: Iterate through all possible starting points (i) for (int i = 0; i < n; i++) { int current_product = 1; // Step 2: Iterate through all possible ending points (j) starting from i for (int j = i; j < n; j++) { current_product *= nums[j]; // Step 3: Calculate product for subarray nums[i...j] if (current_product > max_product) { max_product = current_product; // Step 4: Update max_product if current_product is greater } } } return max_product; } int main() { int nums1[] = {2, 3, -2, 4}; int n1 = sizeof(nums1) / sizeof(nums1[0]); printf("Array: [2, 3, -2, 4], Max Product: %d\n", maxProductBruteForce(nums1, n1)); int nums2[] = {-2, 0, -1}; int n2 = sizeof(nums2) / sizeof(nums2[0]); printf("Array: [-2, 0, -1], Max Product: %d\n", maxProductBruteForce(nums2, n2)); int nums3[] = {-1, -2, -9, -6}; int n3 = sizeof(nums3) / sizeof(nums3[0]); printf("Array: [-1, -2, -9, -6], Max Product: %d\n", maxProductBruteForce(nums3, n3)); int nums4[] = {6, -3, -10, 0, 2}; int n4 = sizeof(nums4) / sizeof(nums4[0]); printf("Array: [6, -3, -10, 0, 2], Max Product: %d\n", maxProductBruteForce(nums4, n4)); return 0; }
Output
Clear
ADVERTISEMENTS