Skip to content

Instantly share code, notes, and snippets.

@nbarnold01
Created November 1, 2015 14:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nbarnold01/6ab7e00d7a31dd0f045d to your computer and use it in GitHub Desktop.
Save nbarnold01/6ab7e00d7a31dd0f045d to your computer and use it in GitHub Desktop.
//
// main.m
// Stock Maximize
//
// Created by Nathan Arnold on 11/1/15.
// Copyright © 2015 Nathan Arnold. All rights reserved.
//
#import <Foundation/Foundation.h>
/*
def calcprofit(stockvalues):
dobuy=[1]*len(stockvalues) # 1 for buy, 0 for sell
prof=0
m=0
for i in range(len(stockvalues)-1,-1,-1): # reverse loop
ai=stockvalues[i] # shorthand name
if m<=ai:
dobuy[i]=0
m=ai
prof+=m-ai
return (prof,dobuy)
*/
long calculateProfit(int stockValues[], int length){
BOOL shouldBuy[length];
long money = 0;
long prof = 0;
//Go reverse order
for (int i = length-1; i >= 0; i--) {
int val = stockValues[i];
if (money <= val) {
shouldBuy[i] = NO;
money = val;
}
prof+=money-val;
}
return prof;
}
void processTestCase() {
int numberOfPrices = 0;
scanf("%d", &numberOfPrices);
int prices[numberOfPrices];
for (int i = 0; i < numberOfPrices; i++){
scanf("%d",&prices[i]);
}
printf("%ld\n",calculateProfit(prices, numberOfPrices));
}
int main(int argc, const char * argv[]) {
@autoreleasepool {
// insert code here...
int numberOfTestCases = 0;
scanf("%d", &numberOfTestCases);
for (int i = 0; i < numberOfTestCases; i++){
processTestCase();
}
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment