zoukankan      html  css  js  c++  java
  • LeetCode 343. Integer Break

    https://leetcode.com/problems/integer-break/

    Given a positive integer n, break it into the sum of at least two positive integers and maximize the product of those integers. Return the maximum product you can get.

    For example, given n = 2, return 1 (2 = 1 + 1); given n = 10, return 36 (10 = 3 + 3 + 4).

    Note: you may assume that n is not less than 2.

    Hint:

    1. There is a simple O(n) solution to this problem.
    2. You may check the breaking results of n ranging from 7 to 10 to discover the regularities.

    数学题。

     1 #include <iostream>
     2 using namespace std;
     3 
     4 class Solution {
     5 public:
     6     int integerBreak(int n) {
     7         if (n == 2) return 1;
     8         if (n == 3) return 2;
     9         
    10         int product = 1;
    11         while (n > 4)
    12         {
    13               n -= 3;
    14               product *= 3;              
    15         }
    16         product *= n;
    17                 
    18         return product;
    19     }
    20 };
    21 
    22 int main ()
    23 {
    24     Solution testSolution;
    25     int result;
    26     
    27     result = testSolution.integerBreak(5);    
    28     cout << result << endl;
    29     
    30     char ch;
    31     cin >> ch;
    32     
    33     return 0;
    34 }
    View Code

    也可以用DP,但自己写的DP想错了,想到分解成MAX(N-2 * 2, N-3 * 3), 应该用MAX(MAX, I-J * J)。

    https://leetcode.com/discuss/102024/java-greedy-o-logn-simple-code-and-o-n-2-dp

  • 相关阅读:
    Python加载声音
    Python 的文件处理
    java学习总结
    Fiddler二次开发 C#
    开发工具 快捷键
    linux / shell /adb
    Java堆栈
    selenium获取接口 HAR
    服务端通过socket向安卓客户端发送shell
    设计模式
  • 原文地址:https://www.cnblogs.com/pegasus923/p/5507138.html
Copyright © 2011-2022 走看看