fork download
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4. #include <limits.h>
  5.  
  6. int min(int x, int y) { return x < y ? x : y; }
  7. int max(int x, int y) { return x > y ? x : y; }
  8.  
  9. int maxProfit(int* prices, int pricesSize) {
  10. int *dp = malloc((pricesSize+1)*sizeof(int)), ans = 0;
  11. dp[pricesSize] = INT_MIN;
  12. for (int i = pricesSize-1; i >= 0; --i)
  13. dp[i] = max(dp[i+1],prices[i]);
  14. for (int b = INT_MAX, i = 1; i < pricesSize; ++i)
  15. b = min(b,prices[i-1]), ans = max(ans,dp[i] -= b);
  16. free(dp);
  17. return ans; }
  18.  
  19. int main(void) {
  20. int *prices, pricesSize;
  21. scanf("%d",&pricesSize), prices = malloc(pricesSize*sizeof(int));
  22. for (int i = 0; i < pricesSize; ++i)
  23. scanf("%d",prices+i);
  24. printf("%d",maxProfit(prices,pricesSize)), free(prices);
  25. return 0; }
  26.  
Success #stdin #stdout 0.01s 5472KB
stdin
6
7 1 5 3 6 4
stdout
5