博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Integer Break
阅读量:4099 次
发布时间:2019-05-25

本文共 974 字,大约阅读时间需要 3 分钟。

题目地址:

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 and not larger than 58.

这种题目就找规律吧,从2开始:

2=1+11
3=2+12
4=2+24
5=3+26
6=3+39
7=3+2+212
8=3+3+218
9=3+3+327
10=3+3+2+236
11=3+3+3+254
好像看出点什么来了,最大积基本都是拆出来以3开头的数字,像7和10这种情况,最后剩余4的时候,一般拆成两个2,而不是拆成3和1,拆成两个2也就是4,所以就不动了。

于是代码可以这么写:

public class IntegerBreak {
public static int integerBreak(int n) { if (n == 2) return 1; if (n == 3) return 2; int res = 1; while (n > 4) { res *= 3; n -= 3; } return res * n; } public static void main(String[] args) { for (int i = 1; i < 58; i++) { System.out.println(i + " " + integerBreak(i)); } }}

转载地址:http://fihii.baihongyu.com/

你可能感兴趣的文章
【TINY4412】U-BOOT移植笔记:(7)SDRAM驱动
查看>>
C++模板
查看>>
【C#】如何实现一个迭代器
查看>>
【C#】利用Conditional属性完成编译忽略
查看>>
【Unity】微信登录后将头像存为bytes,将bytes读取成sprite图片
查看>>
【Unity】使用GPS定位经纬度
查看>>
如何高效学习动态规划?
查看>>
动态规划法(六)鸡蛋掉落问题(一)
查看>>
算法数据结构 思维导图学习系列(1)- 数据结构 8种数据结构 数组(Array)链表(Linked List)队列(Queue)栈(Stack)树(Tree)散列表(Hash)堆(Heap)图
查看>>
【机器学习】机器学习系统SysML 阅读表
查看>>
最小费用流 Bellman-Ford与Dijkstra 模板
查看>>
实现高性能纠删码引擎 | 纠删码技术详解(下)
查看>>
scala(1)----windows环境下安装scala以及idea开发环境下配置scala
查看>>
zookeeper(3)---zookeeper API的简单使用(增删改查操作)
查看>>
zookeeper(4)---监听器Watcher
查看>>
mapReduce(3)---入门示例WordCount
查看>>
hbase(3)---shell操作
查看>>
hbase(1)---概述
查看>>
hbase(5)---API示例
查看>>
SSM-CRUD(1)---环境搭建
查看>>