java - Find complexity of algorithm using step count -
first of - yes, have read several posts here on so, other places estimating complexity of algorithm.
i have read this, this , this, others
i want try algorithm wrote finds largest rectangle, see if understood @ i've read.
public static long getlargestrectangle(long[] arr, int index, long max) { int count = 1; //1 step * 1 int = index - 1; //1 step * 1 int j = index + 1; //1 step * 1 if(index == arr.length-1) return max; //1 step * 2 while(i > -1 && arr[index] <= arr[i]) { //1 step * (n+1) count++; //1 step * n i--; //1 step * n } while(j <= arr.length-1 && arr[index] <= arr[j]) { //1 step * (n+1) count++; //1 step * n j++; //1 step * n } max = (max < (arr[index] * count) ? (arr[index] * count) : max); //1 step * 7 return getlargestrectangle(arr, index + 1, max); //1 step * 1 } //total number of steps: 1 + 1 + 1 + (n + 1) + n + n + (n + 1) + n + n + 7 //=> 6n + 12 = o(n) ? am way off here? i'd love insight.
edit
like this?
t(n) = o(n) + t(n+1) t(n) = o(n) + o(n) + t(n+2) t(n) = o(n) + o(n) + o(n) + t(n+3) t(n) = * o(n) + (n+i) t(n) = n * o(n) + (n+n) = o(n^2) if wrong, i'd appreciate if update answer , show me.
am way off here? i'd love insight.
i afraid :(
return getlargestrectangle(arr, index + 1, max); //1 step * 1 this above not 1 step, recursive invokation of method. method "shrinks" array 1 element, step costs t(n-1), t(.) time complexity of algorithm.
combining have, get
t(n) = t(n-1) + o(n) solving recurrence formula give algorithm's complexity.
note: t(n) = t(n-1) + o(n) syntatic sugar, should have been t(n) <= t(n-1) + const*n constant const, since cannot add set (o(n)) scalar (t(n-1)).
also note: n!=n. n changes on time, n initial length of array. because algorithm traversing n (index) 0, , n n.
this not change time complexity in terms of big o notation, however.
Comments
Post a Comment