For example we have array of meeting objects:

const data = [
{ name: "m1", hours: },
{ name: "m2", hours: },
{ name: "m3", hours: },
{ name: "m4", hours: },
{ name: "m5", hours: }
];

For a day, 8 hours, we want to take as any meetings as possible:

const res = optimizeMeetings(data, );

You should write function 'optimizeMeetings', get the results of selected meetings to attend.

This problem is the same as Knapack problem, we can construct a table:

hours / total 1 2 3 4 5 6 7 8
2  0  2  2  2  2  2  2
4  0  2  2  4  4  6  6  6
3  0  2  3  4  5  6  7 7
3  0  2  3  4  5  6  7  8
1  1  2  3  4  5  6  7 8

The max hours we can take is the last row & col value, which in the end should be 8.

Then we should trace back the table to find which items should be included.

Final Code:

/**@description
* When we have our result for Knapsack problem, we want to back trace to get the selected items.
*
* What we need to do is trace form last item of the memo, moving up
*/
const backTrace = (hours, totalHours, memo) => {
function helper(memo, row, col) {
let current = memo[row][col];
let selected = [];
while (current >= && row >= && col >= ) {
// If we reach the first row, then check whether we have the remaining?
// If yes then we need to add this row item into final result
if (row === && current !== ) {
selected.push(row);
break;
} let sameRowPrevCol = memo[row][col - ];
let prevRowSameCol = memo[row - ][col]; if (current !== sameRowPrevCol && prevRowSameCol !== current) {
// Item should be selected if the value with sibling values are differnet
selected.push(row);
// calcuate the remaining
col = current - hours[row] - ;
row = row - ;
} else if (prevRowSameCol === current && current !== sameRowPrevCol) {
// current is coming from previous row with the same column, reset row
row = row - ;
} else if (current === sameRowPrevCol && prevRowSameCol !== current) {
// current is coming from previous column with the same row, reset column
col = col - ;
}
// Update current with new row and new column
current = memo[row][col];
}
return selected;
} return helper(memo, hours.length - , totalHours.length - );
}; const getMaxHours = (hours, totalHours) => {
let memo = [...new Array(hours.length)].map(
x => new Array(totalHours.length)
);
function helper(hours, totalHours, memo) {
for (let row in hours) {
const value = hours[row];
for (let col in totalHours) {
// Fill in the first row
if (!memo[row - ]) {
memo[row][col] = value <= totalHours[col] ? value : ;
continue;
} // if the current value is larger than constrain, we use previous value
const prevRowSameCol = memo[row - ][col];
if (value > totalHours[col]) {
memo[row][col] = prevRowSameCol;
continue;
} // if the current value is equal to constrain, then Max{value, prevRowSameCol}
if (value === totalHours[col]) {
memo[row][col] = Math.max(value, prevRowSameCol);
} // if the current value is smaller than constrain
// Math {value + memo[row - 1][diff]: where diff is constrain-value, prevRowSameCol}
if (value < totalHours[col]) {
const diff = totalHours[col] - value - ;
memo[row][col] = Math.max(
prevRowSameCol,
value + memo[row - ][diff]
);
}
}
}
return memo;
}
memo = helper(hours, totalHours, memo);
const selectedIndex = backTrace(hours, totalHours, memo); return {
memo,
selectedIndex
};
}; function* genearteNumberAry(start, num) {
let i = start;
while (i <= num) {
yield i;
i++;
}
} /**
* Main
*/
/**
* @param meetings: [{name: string, hours: number}]
* @param haveHours: number
*
* @returns [meetings]
*/
function optimizeMeetings(meetings, haveHours) {
const hours = meetings.map(m => m.hours);
const haveHoursAry = Array.from(genearteNumberAry(, haveHours));
const { selectedIndex } = getMaxHours(hours, haveHoursAry);
return selectedIndex.map(i => meetings[i]);
} const data = [
{ name: "m1", hours: },
{ name: "m2", hours: },
{ name: "m3", hours: },
{ name: "m4", hours: },
{ name: "m5", hours: }
]; const res = optimizeMeetings(data, );
console.log(JSON.stringify(res)); // [{"name":"m4","hours":3},{"name":"m3","hours":3},{"name":"m1","hours":2}]

[Algorithm] Meeting hour optimization (Kanpsack problem) and Dynamic programming的更多相关文章

  1. Codeforces 1503C Travelling Salesman Problem(Dynamic Programming)

    题意 大家都是优秀生,这点英文还是看得懂的:点此看题 题解 由于旅行路线成一个环,所以从哪里出发不重要,我们把景点按照 a i a_i ai​ 排序,不妨就从左边最小的出发.基础的旅行费用 c i c ...

  2. hdu 4223 Dynamic Programming?

    Dynamic Programming? Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/65536 K (Java/Oth ...

  3. hdu 4972 A simple dynamic programming problem(高效)

    pid=4972" target="_blank" style="">题目链接:hdu 4972 A simple dynamic progra ...

  4. [Optimization] Dynamic programming

    “就是迭代,被众人说得这么玄乎" “之所以归为优化,是因为动态规划本质是一个systemetic bruce force" “因为systemetic,所以比穷举好了许多,就认为是 ...

  5. [Optimization] Advanced Dynamic programming

    这里主要是较为详细地理解动态规划的思想,思考一些高质量的案例,同时也响应如下这么一句口号: “迭代(regression)是人,递归(recursion)是神!” Video series for D ...

  6. HDU-4972 A simple dynamic programming problem

    http://acm.hdu.edu.cn/showproblem.php?pid=4972 ++和+1还是有区别的,不可大意. A simple dynamic programming proble ...

  7. 以计算斐波那契数列为例说说动态规划算法(Dynamic Programming Algorithm Overlapping subproblems Optimal substructure Memoization Tabulation)

    动态规划(Dynamic Programming)是求解决策过程(decision process)最优化的数学方法.它的名字和动态没有关系,是Richard Bellman为了唬人而取的. 动态规划 ...

  8. 最优化问题 Optimization Problems & 动态规划 Dynamic Programming

    2018-01-12 22:50:06 一.优化问题 优化问题用数学的角度来分析就是去求一个函数或者说方程的极大值或者极小值,通常这种优化问题是有约束条件的,所以也被称为约束优化问题. 约束优化问题( ...

  9. [Algorithms] Using Dynamic Programming to Solve longest common subsequence problem

    Let's say we have two strings: str1 = 'ACDEB' str2 = 'AEBC' We need to find the longest common subse ...

随机推荐

  1. android 后台 activity 被系统回收 保存状态

    韩梦飞沙  韩亚飞  313134555@qq.com  yue31313  han_meng_fei_sha 活动被系统回收, 要保存状态 ,用到 活动的 在保存实例时候 的 这个方法. 当系统异常 ...

  2. 【20181031T1】一串数字【分解质因数+贪心】

    题面 [错解] 立方就是所有质因子次数都是3的倍数嘛 发现1e5的三次根很小,可以枚举所有和这个数乘起来是完全立方数的(flag*1) 然后--连条边跑最大独立集? 不对啊是NP问题(实际上是个二分图 ...

  3. [CodeChef-QTREE]Queries on tree again!

    题目大意: 给定一个环长为奇数的带权基环树,支持以下两种操作: 1.两点间最短路取反: 2.两点间最短路求最大子段和. 思路: 首先找出环,然后对每一个外向树轻重链剖分, 用线段树维护每一个区间的和. ...

  4. Linux重新学习

    一.由来 unix到minix到linux 1991正式发行 1.内核版本:linux核心版本 linux内核官网www.kernel.org 2.发行版本:比如redhat.centOS.suse. ...

  5. Codeforces Round #351 (VK Cup 2016 Round 3, Div. 2 Edition) C. Bear and Colors 暴力

    C. Bear and Colors 题目连接: http://www.codeforces.com/contest/673/problem/C Description Bear Limak has ...

  6. BZOJ 1191: [HNOI2006]超级英雄Hero 匈牙利算法

    1191: [HNOI2006]超级英雄Hero Time Limit: 2 Sec  Memory Limit: 256 MBSubmit: xxx  Solved: 2xx 题目连接 http:/ ...

  7. ZOJ 1940 Dungeon Master 三维BFS

    Dungeon Master Time Limit:1000MS     Memory Limit:65536KB     64bit IO Format:%I64d & %I64u Desc ...

  8. Swift3.0字符串相关操作

    以下有关字符串的常用操作都可直接复制到Xcode中进行验证,如发现错误,请在评论区留言指正! 1.字符串的定义 var str1="hello, swift." //字符串变量 相 ...

  9. PWM DAC vs. Standalone

    http://analogtalk.com/?p=534 http://analogtalk.com/?p=551 Posted by AnalogAdvocate on April 09, 2010 ...

  10. BeeProg2C Extremely fast universal USB interfaced programmer

    http://www.elnec.com/products/universal-programmers/beeprog2c/ FPGA based totally reconfigurable 48  ...