算法导论(Exercise 4.1-5)

here are two ways:

first,we could set a variable "temp" which equals zero,and we could get the element of  the array one by one.Every time we get a number,we must judge,if temp is less than or equal to zero.If temp<=0, it means that the sum of the previous sequence could not give any contribution to the all possible remaining sequence,so we set it to current value we visit.Or we add current element to the variable-----temp.And we compare temp with the variable res which is used to store the result.If temp is greater than res,we should assign the value of temp to res.  

Apart from the previous solutions,we could do it  another way:As for any array elem[1......j],when we read the new element elem[j+1],we could find that the maximum sum could only be the maximum sum of subsequence of elem[1......j] or the sum of elem[i......j+1],so we use temp to store the sum of  sequence we have travesed,and we also use the variable "before" to represent the previous minimum sum of sequence.And we use (temp-before) to compare with res,and update res if (temp-before>res),and we also upate the variable "before" if (temp<before).We initialize "before" to 0(it is very important)


#include<iostream>
#include<vector>
#include<string>
#include<set>
#include<map>
#include<unordered_set>
#include<unordered_map>
#include<algorithm>
#include<xfunctional>
using namespace std;

int find_maxsum1(vector<int>& elem){
	int sum = INT_MIN;
	int temp = 0;
	for (int i = 0; i < elem.size(); i++){
		if (temp <= 0) temp = elem[i];
		else temp += elem[i];
		if (temp > sum) sum = temp;
	}
	return sum;
}

int find_maxsum2(vector<int>& elem){
	int before = 0;
	int max_sum = INT_MIN;
	int temp = 0;
	for (int i = 0; i < elem.size(); i++){
		temp += elem[i];
		if (temp - before > max_sum){
			max_sum = temp - before;
		}
		if (before > temp){
			before = temp;
		}
	}
	return max_sum;
}


int main(){
	int n;
	cout << "Input the amount of the element:";
	cin >> n;
	vector<int> elem(n,0);
	for (int i = 0; i < n; i++) cin >> elem[i];
	int res1 = find_maxsum1(elem);
	int res2 = find_maxsum2(elem);
	cout << "The result: " << res1 << endl;
	cout << "The result: " << res2 << endl;
	system("pause");
	return 0;
}

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值