Explorar el Código

April Week 1 Done

master
Lachlan Jacob hace 5 años
padre
commit
6a27283d67
Se han modificado 3 ficheros con 81 adiciones y 0 borrados
  1. 50
    0
      122/main.c
  2. 26
    0
      122/problem.txt
  3. 5
    0
      122/run.sh

+ 50
- 0
122/main.c Ver fichero

@@ -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;
}

+ 26
- 0
122/problem.txt Ver fichero

@@ -0,0 +1,26 @@
Say you have an array for which the ith element is the price of a given stock on day i.

Design an algorithm to find the maximum profit. You may complete as many transactions as you like (i.e., buy one and sell one share of the stock multiple times).

Note: You may not engage in multiple transactions at the same time (i.e., you must sell the stock before you buy again).

Example 1:

Input: [7,1,5,3,6,4]
Output: 7
Explanation: Buy on day 2 (price = 1) and sell on day 3 (price = 5), profit = 5-1 = 4.
Then buy on day 4 (price = 3) and sell on day 5 (price = 6), profit = 6-3 = 3.

Example 2:

Input: [1,2,3,4,5]
Output: 4
Explanation: Buy on day 1 (price = 1) and sell on day 5 (price = 5), profit = 5-1 = 4.
Note that you cannot buy on day 1, buy on day 2 and sell them later, as you are
engaging multiple transactions at the same time. You must sell before buying again.

Example 3:

Input: [7,6,4,3,1]
Output: 0
Explanation: In this case, no transaction is done, i.e. max profit = 0.

+ 5
- 0
122/run.sh Ver fichero

@@ -0,0 +1,5 @@
#!/bin/bash

gcc -o main main.c
./main
rm main

Cargando…
Cancelar
Guardar