文章

116

粉丝

69

获赞

655

访问

82.0k

头像
股票交易(常规暴力和贪心) 题解:
P1979 贵州大学2024年机试题
发布于2025年3月12日 14:49
阅读数 34

常规 O(N^2):

#include<bits/stdc++.h>
using namespace std;

const int N = 1e4 + 10;
int n, a[N];

int main()
{
	cin >> n;

	for(int i = 1; i <= n; i ++)
		scanf("%d", &a[i]);
	
	int res = INT_MIN;
	for(int i = 1; i < n; i ++)
		for(int j = i + 1; j <= n; j ++)
			res = max(res, a[j] - a[i]);
	
	cout << res << endl;
	
	return 0;
}

贪心O(N): 

#include<bits/stdc++.h>
using namespace std;
typedef long long LL;

LL a, ans;
int n;

int main()
{
    cin >> n;

    a = LLONG_MAX, ans = LLONG_MIN;
    for(int i = 1; i <= n; i ++)
    {
        LL x; cin >> x;
        a = min(a, x);
        ans = max(ans, x - a);    
    }
    cout << ans;
    
    return 0;
}

 

登录查看完整内容


登录后发布评论

暂无评论,来抢沙发