Problem: divide the specified sequence into three parts, take the maximum value of each part, and then obtain the maximum Max from the maximum value of three parts. How can we divide them to minimize Max?
Input: 1, 2, 3, 4, 5
Division: 1, 2, 3 | 4 | 5
The maximum value is 6.
Idea: two pointers P1, P2, P1 index in [0, len-2), P2 index in [P1 + 1, len-1), the last index range [p2 + 1, len-1]
Implementation:
Array.prototype.sum = function(i,j){i = i == undefined ? 0 : i;j = j == undefined ? 0 : j;var s = 0;for(var k = i;k <=j ;k++){s+=this[k];}return s;}function f(arr){var result = {val:undefined,p1:"",p2:""};for(var p1 = 0;p1<arr.length-2;p1++){var s1 = arr.sum(0,p1);for(var p2 = p1+1;p2<arr.length-1;p2++){var s2 = arr.sum(p1+1,p2);var s3 = arr.sum(p2+1,arr.length-1);var min = Math.max(Math.max(s1,s2),s3);if(p1==2){console.log("min : "+min +",p1:"+p1+",p2:"+p2+",s2:"+s2+",s3:"+s3);}if(!result.val || result.val > min){result.val = min;result.p1 = p1;result.p2=p2;}}}return result;}console.log(f(new Array(1,2,3,4,5)));
Sequence partitioning-minimizing its maximum value