Be Excel in C Language – Part 2: Container with Most Water

Medium level of brute force tactics.

Another day, another new challenge. Here, the second installment is Be Excel in C language series. To manually translate what I did in Java to C, I re-learn the core concept of coding all over again. Keep coding, keep learning. Here we go!

So, this is the second post on Be Excel in C Language. Just like what I wrote on Road to Google – Part 2: Container with Most Water, I did the same operations in C.

Question:

You are given an array of positive integers where each integer represents the height of a vertical line on a chart.

Find two lines that together with the x-axis form a container that would hold the most significant amount of water.

Return the area of water it would hold.

What is this?

If you have no idea what the question is asking for, don’t worry. I wrote a detailed explanation of it in the aforementioned post.

So, here is another brute-force approach to solving the problem.

image 01

Difference from Java 1: Argument numbers

In Java, maxArea function’s argument was one: the array.

public static int maxArea(int[] a)

On the other hand, C’s maxArea function receives two arguments: the array and the array’s length.

int maxArea(int *nums, int len)

While Java’s int-type variable can access its length by specifying a.length, C’s counterpart can’t. Instead, it has to receive the number as the array’s length.

Difference from Java 2: Max/min functions

You can take advantage of Java’s input/output libraries such as max and min that figure out both max/min numbers.

area = Math.max(area, Math.min(a[i], a[j]) * (j - i));

Contrary, you may have to write the code from the ground up all by yourself to figure out max/min numbers.

#define MAX(x, y) (((x) > (y)) ? (x) : (y))
#define MIN(x, y) (((x) < (y)) ? (x) : (y))

The mechanism of MAX, is: check if x is bigger than y.

if true, the program will move to the right side of ? (x) : (y), and return x (if not y).

The mechanism of MIN, is: check if x is smaller than y.

if true, the program will move to the right side of ? (x) : (y), and return y (if not x).

Afterthoughts:

Those are two noticeable differences I can think of.

Anyways, happy coding!

#include <stdio.h>
#include <math.h>

#define MAX(x, y) (((x) > (y)) ? (x) : (y))
#define MIN(x, y) (((x) < (y)) ? (x) : (y))

int maxArea(int *nums, int len) {
    nums[5];
    int maxArea = 0;
    for (int i = 0; i < len - 1; i++) {
        for (int j = i + 1; j < len; j++) {
            maxArea = MAX(maxArea, MIN(nums[j], nums[i]) * (j - i));
        }
    }
    return maxArea;
}

void main() {
    int nums[5] = {7,1,2,3,9};
    int len = sizeof(nums) / sizeof(nums[0]);
    printf("%d\n",maxArea(nums, len));
}

Leave a Reply