Created
September 14, 2016 01:35
-
-
Save anupamkumar/f25ae059854712cc247f104b15217a7f to your computer and use it in GitHub Desktop.
Maximize value of (arr[i] – i) – (arr[j] – j) in an array
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Maximize value of (arr[i] – i) – (arr[j] – j) in an array | |
// Given an array, arr[] find the maximum value of (arr[i] – i) – (arr[j] – j) where i is not equal to j. | |
// Where i and j vary from 0 to n-1 and n is size of input array arr[]. | |
// Examples: | |
// Input : arr[] = {9, 15, 4, 12, 13} | |
// Output : 12 | |
// We get the maximum value for i = 1 and j = 2 | |
// (15 - 1) - (4 - 2) = 12 | |
// Input : arr[] = {-1, -2, -3, 4, 10} | |
// Output : 6 | |
// We get the maximum value for i = 4 and j = 2 | |
// (10 - 4) - (-3 - 2) = 11 | |
///Analysis | |
// pre-compute will help reduce the runtime but increase the Space requirement to O(2N) but that's still acceptable as space will still be O(N) | |
/// and time will also be O(N) | |
// My solution | |
// (1) I ll precompute arr[i] - i for all elements and save it in another array B | |
// (2) I ll find min(B) and max(B) | |
// (3) difference of max(B) and min(B) will be the maximum value | |
// steps 1,2,3 all are of the order O(N) timewise, therefore the algorithm is O(N) overall | |
function findDiffArray(inputArray) { | |
diffArray = []; | |
for(i=0;i<inputArray.length;i++) { | |
diffArray[i] = inputArray[i] -i; | |
} | |
return diffArray; | |
} | |
function minValInArray(inputArray) { | |
var min=Number.MAX_VALUE; | |
for(i=0;i<inputArray.length;i++) { | |
if (min > inputArray[i]) | |
min = inputArray[i]; | |
} | |
return min; | |
} | |
function maxValInArray(inputArray) { | |
var max=Number.MIN_VALUE; | |
for(i=0;i<inputArray.length;i++) { | |
if (max < inputArray[i]) | |
max = inputArray[i]; | |
} | |
return max; | |
} | |
function solution(inputArray) { | |
da = findDiffArray(inputArray); | |
minv=minValInArray(da); | |
maxv=maxValInArray(da); | |
return maxv - minv; | |
} | |
///////////////////////// | |
///verification | |
///////////////////////// | |
console.log(solution([9, 15, 4, 12, 13])); | |
console.log(solution([-1, -2, -3, 4, 10])); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment