Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I am a college student and prefer java.I know core c. The problem is in many coding competition like codechef problem, spoj etc, most of the coder code in c++ which take storage of 2 or 3 MB comparatively 1400 MB in java. For Example storing two arrays of length pow(10,9), and then performing a certain operation based on the data collected in two arrays take vast memory in java. Is it possible to adopt any strategy to optimize the code? e.g.

Note: Constraint for value of 'n' : 1 ≤ N ≤ pow(10,9)

public void solve(InputReader in, PrintWriter out) {
    try {
        int n = in.nextInt();
        int k = in.nextInt();
        int[] time = new int[n];
        int[] profit = new int[n];
        int res = 0;
        int max = 0;
        for (int i = 0; i < n; i++) {
            time[i] = in.nextInt();
            profit[i] = in.nextInt();
        }
        for (int i = 1; i < n; i++) {
            double v1 = ((int) k / ((time[max]))) * (profit[max]);
            double v2 = (((int) k / ((time[i]))) * (profit[i]));
            if (v1 < v2) {
                max = i;
            }
        }

        res = ((int) k / time[max]) * profit[max];
        out.println(res);

    } catch (Exception ex) {
        return;
    }
}

EDITED 24 AUGUST 2017 It's an old question, however, I am adding more information now. Look at the picture below:

enter image description here

Here even on page 124 of 610 most successful answers are on the basis of languages like c or c++ as they acquire very less memory.

However, when I look into java solution, the memory acquired by them is pretty high.

java screenshot

As per the @Peter answer, it is clear that memory will be occupied in any language if we store it in an array of length pow(10,9)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
252 views
Welcome To Ask or Share your Answers For Others

1 Answer

Two arrays of 10^9 will use GBs of memory in any language. e.g. 2 * int[10^9] requires 8 GB of memory, whether you use C or Java.

The real solution is likely to be to not create the arrays at all as they don't appear to be needed. You can process the data as you read it. This will use next to no memory whether you use Java or C.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...