Instead of rotating the array, rotate the indices. O(n^2) solution


  • 0
    D

    public int maxRotateFunction(int[] nums) {

        if(nums.length == 0){
            return 0;    
        }
        
        int index = 0;
    	int max = Integer.MIN_VALUE;
    	int iter = 0;
    	
    	while(iter < nums.length){
    		
    		int value = 0;
    		
    		for(int i = 0; i < nums.length; i++){
    			value += nums[i] * index++;
    			if(index >= nums.length){
    				index = 0;
    			}
    		}
    		
    		if(value > max){
    			max = value;
    		}
    		
    		iter++;
    		index = iter;
    	}
    	
    	return max;
        
    }

Log in to reply
 

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