Find best container – Cracking Code
現在給某個容量(double capacity), 還有一個array(double[] weights), 和int numOfContainers 主要是要在array中選出兩個weights總和小於等於capacity但最接近capacity.然後指定到一個Container object並且return
Extended:
How about select k elements, or any number?
-- K sum closest
Read full article from Find best container – Cracking Code
現在給某個容量(double capacity), 還有一個array(double[] weights), 和int numOfContainers 主要是要在array中選出兩個weights總和小於等於capacity但最接近capacity.然後指定到一個Container object並且return
- public static Container findOptimalWeight(double[] weights, double target) {
- Container result = new Container(0, 0);
- if (weights == null || weights.length < 2) return result;
- Arrays.sort(weights);
- int lo = 0, hi = weights.length - 1, first = lo, second = hi;
- while (lo < hi) {
- if (weights[lo] + weights[hi] == target) {
- first = lo;
- second = hi;
- break;
- } else if (weights[lo] + weights[hi] > target) {
- hi --;
- } else {
- if (target < weights[first] + weights[second] || target - (weights[first] + weights[second]) > target - (weights[lo] + weights[hi])) {
- first = lo;
- second = hi;
- }
- lo ++;
- }
- }
- result.first = weights[first];
- result.second = weights[second];
- return result;
- }
Extended:
How about select k elements, or any number?
-- K sum closest
Read full article from Find best container – Cracking Code