剪绳子

问题:给你一根长度为n的绳子,请把绳子剪成m段(m,n都是整数,n>1,m>1),每段绳子的长度记为k[0],k[1],...,k[m]。请问k[0]*k[1]*...k[m]可能的最大乘积是多少?

#include<iostream>
#include<math.h>
using namespace std;
int maxProductAfterCutting_solution(int length);
int maxProductAfterCutting_solution2(int length);
int main()
{
	cout <<"0: "<< maxProductAfterCutting_solution(0) <<endl;
	cout <<"1: "<< maxProductAfterCutting_solution(1) << endl;
	cout <<"2: "<< maxProductAfterCutting_solution(2) << endl;
	cout <<"3: "<< maxProductAfterCutting_solution(3) << endl;
	cout <<"4: "<< maxProductAfterCutting_solution(4) << endl;
	cout <<"5: "<< maxProductAfterCutting_solution(5) << endl;
	cout <<"6: "<< maxProductAfterCutting_solution(6) << endl;
	cout <<"7: "<< maxProductAfterCutting_solution(7) << endl;
	cout << "8: " << maxProductAfterCutting_solution(8) << endl;
	cout << "9: " << maxProductAfterCutting_solution(9) << endl;
	cout << "10: " << maxProductAfterCutting_solution(10) << endl;
	cout << "11: " << maxProductAfterCutting_solution(11) << endl;
	system("pause");
    return 0;
}

int maxProductAfterCutting_solution(int length) {

	if (length < 2) {
		return 0;
	}
	if (length==2)
	{
		return 2;
	}
	if (length ==3)
	{
		return 3;
	}
	int *products = new int[length +1];
	products[0] = 0;
	products[1] = 1;
	products[2] = 2;
	products[3] = 3;
	int max = 0;
	for (size_t i = 4; i <=length; i++)
	{
		int mid = i / 2;
		max = 0;
		for (size_t j = 1; j <= mid; j++)
		{
			int tmp = products[j] * products[i - j];
			if (max< tmp)
			{
				max = tmp;
			}
			products[i] = max;
		}
	}
	max = products[length];
	delete[] products;
	return max;
}

int maxProductAfterCutting_solution2(int length) {
	if (length<2)
	{
		return 0;
	}
	if (length ==2)
	{
		return 2;
	}
	if (length == 3)
	{
		return 3;
	}
	int time3 = length / 3;
	int time4 = 0;
	if (length%3 ==1)
	{
		time3 = time3 - 1;
		time4 = 1;
	}
	int time2 = (length - 3 * time3)/2;
	return (pow(3, time3) * pow(2, time2));
	
}


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值