Fancy DSA Fancy DSA
数据结构
算法
LeetCode
  • 关于
  • 导航 (opens new window)
  • 分类
  • 标签
  • 归档
设计模式 (opens new window)
博客 (opens new window)
GitHub (opens new window)

Jonsam NG

想的更多,也要想的更远
数据结构
算法
LeetCode
  • 关于
  • 导航 (opens new window)
  • 分类
  • 标签
  • 归档
设计模式 (opens new window)
博客 (opens new window)
GitHub (opens new window)
  • 开始上手
  • Plan 计划
  • Roadmap 路线
  • 算法简介
  • Sort 排序

  • Search 搜索

  • Recursive 递归

  • Graph 图

  • Tree 树

  • Math 数学

  • Hash 哈希

  • String 字符串

  • BitManipulation 位操纵

  • Backtracking 回溯

  • DynamicProgramming 动态规划

    • ClimbingStairs [爬楼梯]
    • CoinChange [钱币兑换]
    • EditDistance [编辑距离]
    • FibonacciNumber [斐波那契数]
    • FindMonthCalendar [月历]
    • KadaneAlgo [最大连续子数组和之Kadane算法]
    • LevenshteinDistance [莱文斯坦距离]
    • LongestCommonSubsequence [最长公共子序列]
    • LongestIncreasingSubsequence [最长递增子序列]
    • LongestPalindromicSubsequence [最长回文子序列]
    • LongestValidParentheses [最长合法括号]
    • MaxNonAdjacentSum [最大非连接子集和]
    • MaxProductOfThree [最大三数积]
      • 介绍
      • 实现
      • 参考
    • MinimumCostPath [最小代价路径]
    • NumberOfSubsetEqualToGivenSum [等和子集]
    • RodCutting [棒材切割问题]
    • Shuf [随机样本]
    • SieveOfEratosthenes [埃拉托斯特尼筛法]
    • SlidingWindow [滑窗]
    • SudokuSolver [数独]
    • TrappingRainWater [接住雨水]
    • TribonacciNumber [翠波那契数]
    • ZeroOneKnapsack [零一背包]
  • Cache 缓存

  • Array 数组

  • Ciphers 密码学

  • Conversions 转换

  • ProjectEuler 欧拉计划

  • 其他

  • 算法
  • DynamicProgramming 动态规划
jonsam
2022-09-26
目录

MaxProductOfThree [最大三数积]

# 介绍

给定一个整数数组,找出你能从三个整数中得到的最大乘积。

Brute Force 方法:

我们可以用三个循环来迭代 arr。

// O(n^3) time
const threeSum = (arr) => {
  let maxProduct = 0;
  for (let i=0; i<arr.length - 2; i++) {
    for (let j=i+1; j<arr.length - 1; j++) {
      for (let k=j+1; k<arr.length; k++) {
        let product = arr[i] * arr[j] * arr[k];
        if (product > maxProduct) {
          maxProduct = product;
        }
      }
    }
  }
  return maxProduct;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

排序法:

如果我们对数组进行排序 -- 我们可以在O(nlogn)O(nlogn)O(nlogn) 时间内完成,那么我们可以简单地将最后的最大的三个整数相乘。

// O(n log n)
const threeSum = (arr) => {
  sortedArr = arr.sort((a, b) => a - b);
  let len = arr.length;
  let maxProduct = sortedArr[len-1] * sortedArr[len-2] * sortedArr[len-3];
  return maxProduct;
}
1
2
3
4
5
6
7

贪婪算法:

如果我们使用贪婪算法,可以获得O(n)O(n)O(n) 的时间。

const threeSum = (arr) => {

    let highest = Math.max(arr[0], arr[1]);
    let lowest  = Math.min(arr[0], arr[1]);
    let highestProductOf2 = arr[0] * arr[1];
    let lowestProductOf2  = arr[0] * arr[1];
    let highestProductOf3 = arr[0] * arr[1] * arr[2];

    for (let i=2; i<arr.length; i++) {
        let current = arr[i];

        highestProductOf3 = Math.max(
            highestProductOf3,
            current * highestProductOf2,
            current * lowestProductOf2
        );

        highestProductOf2 = Math.max(
            highestProductOf2,
            current * highest,
            current * lowest
        );

        lowestProductOf2 = Math.min(
            lowestProductOf2,
            current * highest,
            current * lowest
        );

        highest = Math.max(highest, current);

        lowest = Math.min(lowest, current);
    }

    return highestProductOf3;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36

还要注意的是,目前的解决方案不能正确处理负数。

# 实现

# JavaScript

/**
 *  Given an array of numbers, return the maximum product
 *  of 3 numbers from the array
 *  https://wsvincent.com/javascript-three-sum-highest-product-of-three-numbers/
 * @param {number[]} arrayItems
 * @returns number
 */
export function maxProductOfThree (arrayItems) {
  // if size is less than 3, no triplet exists
  const n = arrayItems.length
  if (n < 3) throw new Error('Triplet cannot exist with the given array')
  let max1 = arrayItems[0]
  let max2 = -1
  let max3 = -1
  let min1 = arrayItems[0]
  let min2 = -1
  for (let i = 1; i < n; i++) {
    if (arrayItems[i] > max1) {
      max3 = max2
      max2 = max1
      max1 = arrayItems[i]
    } else if (max2 === -1 || arrayItems[i] > max2) {
      max3 = max2
      max2 = arrayItems[i]
    } else if (max3 === -1 || arrayItems[i] > max3) {
      max3 = arrayItems[i]
    }
    if (arrayItems[i] < min1) {
      min2 = min1
      min1 = arrayItems[i]
    } else if (min2 === -1 || arrayItems[i] < min2) {
      min2 = arrayItems[i]
    }
  }
  const prod1 = max1 * max2 * max3
  const prod2 = max1 * min1 * min2
  return Math.max(prod1, prod2)
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38

注意,max2、max3、min2 需要尽快初始化以免乘以 -1 出错。

# 参考

  • JavaScript Three Sum: Find the Highest Product of Three Numbers - Will Vincent (opens new window)
编辑 (opens new window)
上次更新: 2022/10/25, 20:46:09
MaxNonAdjacentSum [最大非连接子集和]
MinimumCostPath [最小代价路径]

← MaxNonAdjacentSum [最大非连接子集和] MinimumCostPath [最小代价路径]→

最近更新
01
0-20题解
10-31
02
本章导读
10-31
03
算法与转换:Part1
10-28
更多文章>
Theme by Vdoing | Copyright © 2022-2022 Fancy DSA | Made by Jonsam by ❤
  • 跟随系统
  • 浅色模式
  • 深色模式
  • 阅读模式