数组中,假定i<k,若a[i]<a[k]且a[i]右侧没有数组元素大于a[k],则认为a[i]与a[k]构成大小对,求数组中所有大小对之和
1条回答 默认 最新
CodeBytes 2023-03-05 10:18关注该回答引用ChatGPT
以下是C++实现,通过一次遍历数组来寻找大小对,时间复杂度为O(n):#include <iostream> #include <vector> using namespace std; int main() { int n; cin >> n; vector<int> a(n); for (int i = 0; i < n; i++) { cin >> a[i]; } int ans = 0, max_num = a[n-1]; for (int i = n-2; i >= 0; i--) { if (a[i] < max_num) { ans += a[i]; } else { max_num = a[i]; } } cout << ans << endl; return 0; }这里使用一个变量max_num来记录数组右侧的最大值,如果当前的数小于max_num,则说明它和右侧的最大值构成了一个大小对,将它加入答案中。否则,更新max_num为当前的数。最后返回答案即可。
解决评论 打赏 举报无用 1