|
|
@@ -0,0 +1,50 @@ |
|
|
|
#include <stdio.h> |
|
|
|
#include <limits.h> |
|
|
|
|
|
|
|
int maxProfit(int*, int); |
|
|
|
int maxProfit(int* prices, int pricesSize){ |
|
|
|
// Each time the direction changes buy/sell at that price if possible |
|
|
|
// only make decision once past the decision point |
|
|
|
// Only count profit once sold |
|
|
|
int profit = 0; |
|
|
|
int buy = 0; // zero will represent looking to buy, 1 will be looking to sell |
|
|
|
int current_stock = -1; // This will represent the value of the current bought stock, to sell, put this into profit var |
|
|
|
int last = INT_MAX; // This will be used to look back |
|
|
|
|
|
|
|
// Apply basic strategy |
|
|
|
for (int i = 0; i < pricesSize; i++) { |
|
|
|
if (buy == 0 && prices[i] > last) { |
|
|
|
buy = 1; // buy this stuff |
|
|
|
current_stock = last; |
|
|
|
} else if (buy == 1 && prices[i] < last) { |
|
|
|
// sell at the last price in retrospect |
|
|
|
buy = 0; |
|
|
|
profit = profit + last - current_stock; |
|
|
|
current_stock = -1; |
|
|
|
} |
|
|
|
last = prices[i]; |
|
|
|
} |
|
|
|
|
|
|
|
// Need to check if we can sell at last price or not |
|
|
|
// i.e. there hasn't been a swing back, it's all up baby |
|
|
|
if (current_stock != -1 && last > current_stock) { |
|
|
|
profit = profit + last - current_stock; |
|
|
|
} |
|
|
|
|
|
|
|
return profit; |
|
|
|
} |
|
|
|
|
|
|
|
int main() { |
|
|
|
int prices[6] = {7, 1, 5, 3, 6, 4}; |
|
|
|
printf("Expected: 7\n"); |
|
|
|
printf("Got: %d\n", maxProfit(prices, 6)); |
|
|
|
/* |
|
|
|
int prices_two[5] = {1, 2, 3, 4, 5}; |
|
|
|
printf("Expected: 4\n"); |
|
|
|
printf("Got: %d\n", maxProfit(prices_two, 5)); |
|
|
|
int prices_three[5] = {7, 6, 4, 3, 1}; |
|
|
|
printf("Expected: 0\n"); |
|
|
|
printf("Got: %d\n", maxProfit(prices_three, 5)); |
|
|
|
*/ |
|
|
|
return 0; |
|
|
|
} |