đĸ Problem 1: Maximum Subarray Sum
đ§ž Output Explanation:
The subarray [4, -1, 2, 1]
in the given array sums up to 6, which is the largest sum achievable from any contiguous subarray.
đģ C Code:
#include <stdio.h>
int main() {
int n, a[100000], maxSum, currSum;
scanf("%d", &n);
for (int i = 0; i < n; i++) scanf("%d", &a[i]);
currSum = maxSum = a[0];
for (int i = 1; i < n; i++) {
currSum = (currSum + a[i] > a[i]) ? currSum + a[i] : a[i];
if (currSum > maxSum) maxSum = currSum;
}
printf("%d\n", maxSum);
return 0;
}
đ Problem 2: Count Inversions
đ§ž Output Explanation:
Inversions are pairs where a larger number appears before a smaller number.
For the input, the inversions are:
- (2,1) at indices (0,2)
- (4,1) at indices (1,2)
- (4,3) at indices (1,3)
đģ C Code:
#include <stdio.h>
int main() {
int n, a[100000], count = 0;
scanf("%d", &n);
for (int i = 0; i < n; i++) scanf("%d", &a[i]);
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
if (a[i] > a[j]) count++;
}
}
printf("%d\n", count);
return 0;
}
đĻ Problem 3: Prefix Sum Query
đ§ž Output Explanation:
Each query asks for the sum of elements between indices L and R.
For example:
- Query 1: sum from 1 to 3 → 1+2+3 = 6
- Query 2: sum from 2 to 4 → 2+3+4 = 9
- Query 3: sum from 3 to 5 → 3+4+5 = 12
đģ C Code:
#include <stdio.h>
int main() {
int n, q, a[100001], prefix[100001] = {0};
scanf("%d %d", &n, &q);
for (int i = 1; i <= n; i++) {
scanf("%d", &a[i]);
prefix[i] = prefix[i-1] + a[i];
}
while (q--) {
int l, r;
scanf("%d %d", &l, &r);
printf("%d\n", prefix[r] - prefix[l-1]);
}
return 0;
}
đ¯ Problem 4: Maximum in Submatrix (2D Array)
đ§ž Output Explanation:
The matrix is divided into all possible K×K submatrices.
For each submatrix, the maximum element is printed:
- Top-left 2x2 submatrix max = 5
- Top-right 2x2 submatrix max = 6
- Bottom-left 2x2 submatrix max = 8
- Bottom-right 2x2 submatrix max = 9
đģ C Code:
#include <stdio.h>
int max(int a, int b) { return a > b ? a : b; }
int main() {
int n, k, a[500][500];
scanf("%d %d", &n, &k);
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++)
scanf("%d", &a[i][j]);
for (int i = 0; i <= n - k; i++) {
for (int j = 0; j <= n - k; j++) {
int mx = a[i][j];
for (int x = 0; x < k; x++)
for (int y = 0; y < k; y++)
mx = max(mx, a[i + x][j + y]);
printf("%d\n", mx);
}
}
return 0;
}
đ Problem 5: Matrix Rotation (90 Degrees Clockwise)
đ§ž Output Explanation:
Rotating the matrix 90° clockwise means:
- The first row becomes the last column,
- The second row becomes the second last column, and so on.
[1 2 3]
becomes the last column from top to bottom.
đģ C Code:
#include <stdio.h>
int main() {
int n, a[1000][1000];
scanf("%d", &n);
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++)
scanf("%d", &a[i][j]);
for (int j = 0; j < n; j++) {
for (int i = n - 1; i >= 0; i--)
printf("%d ", a[i][j]);
printf("\n");
}
return 0;
}
āĻোāύ āĻŽāύ্āϤāĻŦ্āϝ āύেāĻ:
āĻāĻāĻি āĻŽāύ্āϤāĻŦ্āϝ āĻĒোāϏ্āĻ āĻāϰুāύ