Weird Java 8 Behavior in solving problem.


  • 1
    C
    	public int canCompleteCircuit(int[] gas, int[] cost) {
        int start = 0;
        int i = 0;
        int runningCost = 0;
        
        int totalGas = 0;
        int totalCost = 0;
        totalGas = Arrays.stream(gas).sum();
        totalCost = Arrays.stream(cost).sum();
       
        //for (int item : gas) totalGas += item;
        //for (int item : cost) totalCost += item;
        
        if (totalGas < totalCost)
        	return -1;
        
        while (start > i || (start == 0 && i < gas.length)) {
        	runningCost += gas[i];
        	if (runningCost >= cost[i]) {
        		runningCost -= cost[i++];
        	} else {
        		runningCost -= gas[i];
        		if (--start < 0) 
        			start = gas.length - 1;
        		runningCost += (gas[start] - cost[start]);
        	}        	
        }
        return start;
    }
    

    I observed a weird result today while coding in Java 8.
    To find sum of arrays, I can either use Arrays.stream(array_name).sum() or run iterative loop and compute the result.
    When I used Arrays.stream(array_name).sum(), I am getting TLE while computing sum by iteration I am getting it Accepted.

    Below is the solution which gave TLE for this problem.

    To get it accepted uncomment the two for loops ..

    //for (int item : gas) totalGas += item;
    //for (int item : cost) totalCost += item;
    

    Uncomment the above and Comment the following code snippet :

     totalGas = Arrays.stream(gas).sum();
    totalCost = Arrays.stream(cost).sum();
    

    Why computing sum using Arrays.stream(gas).sum() caused TLE ?? While using iteration to computer sum got it Accepted? I have no idea how come streaming be slow ??


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.