题解 | 买卖股票的最好时机(一)

买卖股票的最好时机(一)

https://www.nowcoder.com/practice/351b87e53d0d44928f4de9b6217d36bb

//  #牛客春招刷题训练营# https://www.nowcoder.com/discuss/726480854079250432
//  动态规划, 当天买入股票的最大收益 = 当天及之后的股票的最高价(后缀最大值) - 当天的股票价, 通过遍历去最大值即可,时间复杂度是O(3n)=O(n)
#include<iostream>
#include<vector>
#include<algorithm>
#define pre(i,j,k) for (int i = j; i < k; i++)
using namespace std;
int main(){
  ios_base::sync_with_stdio(false),cin.tie(0),cout.tie(0);
  int n;
  cin >> n;
  vector<int> sufmax(n + 1), a(n);
  pre(i, 0, n) cin >> a[i];
  for (int i = n - 1; i >= 0; i--) sufmax[i] = max(sufmax[i + 1], a[i]);
  int ans = 0;
  pre(i, 0, n) ans = max(ans, sufmax[i] - a[i]);
  cout << ans;
  return 0;
}

全部评论

相关推荐

06-07 00:00
已编辑
腾讯_后端开发
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务