股票买卖
暴力循环法,两个for循环,求出两两的差值,再找出最大的
function max_profit(prices) {
let max = 0; //记录股票的最大收益
let ind_best = []; //记录买进和卖出的时间点
for (let i = 0; i < prices.length - 1; i++) {
for (let j = i + 1; j < prices.length; j++) {
if (prices[j] - prices[i] > max) {
max = prices[j] - prices[i];
ind_best[0] = i;
ind_best[1] = j;
}
}
}
return ind_best;
}
let prices = [10, 11, 7, 10, 6];
const resule = max_profit(prices);
console.log(resule);
分治算法:
一:将问题分解为若干简单的子问题
二:通过递归寻求各个子问题的解
三:合并各个子问题的解,从而得到原问题的解
先将数组分解成左右两半,求出两边各自的最优解;
再考虑最优解跨界的情况,此时只需要找出左边序列的最小值和右边序列的最大值便可
function max_profit(prices) {
let length = prices.length;
//采用递归有边界条件
if (prices.length < 2) {
return 0;
}
Math.max;
let mid = parseInt(length / 2);
const left = max_profit(prices.slice(0, mid));
const right = max_profit(prices.slice(mid, length));
const left_right =
Math.max(...prices.slice(mid, length)) - Math.min(...prices.slice(0, mid));//跨界情况
return Math.max(left, right, left_right);
}
let prices = [10, 11, 7, 10, 6];
const result = max_profit(prices);
console.log(result);