My LeetCode grinding. Trying to do a problem a day.
您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. #include <stdio.h>
  2. #include <limits.h>
  3. int maxProfit(int*, int);
  4. int maxProfit(int* prices, int pricesSize){
  5. // Each time the direction changes buy/sell at that price if possible
  6. // only make decision once past the decision point
  7. // Only count profit once sold
  8. int profit = 0;
  9. int buy = 0; // zero will represent looking to buy, 1 will be looking to sell
  10. int current_stock = -1; // This will represent the value of the current bought stock, to sell, put this into profit var
  11. int last = INT_MAX; // This will be used to look back
  12. // Apply basic strategy
  13. for (int i = 0; i < pricesSize; i++) {
  14. if (buy == 0 && prices[i] > last) {
  15. buy = 1; // buy this stuff
  16. current_stock = last;
  17. } else if (buy == 1 && prices[i] < last) {
  18. // sell at the last price in retrospect
  19. buy = 0;
  20. profit = profit + last - current_stock;
  21. current_stock = -1;
  22. }
  23. last = prices[i];
  24. }
  25. // Need to check if we can sell at last price or not
  26. // i.e. there hasn't been a swing back, it's all up baby
  27. if (current_stock != -1 && last > current_stock) {
  28. profit = profit + last - current_stock;
  29. }
  30. return profit;
  31. }
  32. int main() {
  33. int prices[6] = {7, 1, 5, 3, 6, 4};
  34. printf("Expected: 7\n");
  35. printf("Got: %d\n", maxProfit(prices, 6));
  36. /*
  37. int prices_two[5] = {1, 2, 3, 4, 5};
  38. printf("Expected: 4\n");
  39. printf("Got: %d\n", maxProfit(prices_two, 5));
  40. int prices_three[5] = {7, 6, 4, 3, 1};
  41. printf("Expected: 0\n");
  42. printf("Got: %d\n", maxProfit(prices_three, 5));
  43. */
  44. return 0;
  45. }