Stock buy and sell

QUESTION

The cost of a stock on each day is given in an array, find the max profit that you can make by buying and selling in those days. \n\nInput:\nFirst line contains number of test cases T. Each test case contain the integer value \”N\” denoting days followed by an array of stock prices in N days.\nOutput:\nThe maximum profit is displayed as shown below. And if there is no profit then print \”\”No Profit\”\”.\n\n\nConstraints:\n1 <=T<=100\n2 <=N<=100\n1 <=arr[i]<=10000.

“TESTCASE_1”: “2\n7\n100 180 260 310 40 535 695\n10\n23 13 25 29 33 19 34 45 65 67\n###—###SEPERATOR—###—\n(0 3) (4 6)\n(1 4) (5 9)”, “TESTCASE_2”: “2\n5\n10 80 60 30 40\n10\n2 1 5 9 3 8 4 5 6 7\n###—###SEPERATOR—###—\n(0 1) (3 4)\n(1 3) (4 5) (6 9)”, “TESTCASE_3”: “4\n7\n100 180 260 310 40 535 695\n10\n23 13 25 29 33 19 34 45 65 67\n5\n10 80 60 30 40\n10\n2 1 5 9 3 8 4 5 6 7\n###—###SEPERATOR—###—\n(0 3) (4 6)\n(1 4) (5 9)\n(0 1) (3 4)\n(1 3) (4 5) (6 9)”, “TESTCASE_4”: “0\n###—###SEPERATOR—###—\n0”, “TESTCASE_5”: “0\n###—###SEPERATOR—###—\n0

ANSWER

#include <stdio.h>
#include<stdlib.h>
int main(){
    int testcases, array_size,i,j,*arr,*test_results;
    //get Testcases
    scanf("%d",&testcases);
    test_results = (int*)malloc(testcases*sizeof(int));
    if(!test_results)
       return -1;
    for(j=0; j<testcases;j++){
        int sum=0,max_sum=0;
        //get array size
        scanf("%d",&array_size);
        arr = (int*)malloc(array_size*sizeof(int));
        if(!arr)
            return -1;
        //populate input array
        for(i=0;i<array_size;i++){
            scanf("%d",&arr[i]);
        }
        int buy_prefix=0; int sell_prefix=0;
        int bought = 0;int sold =0; 
        for(i=0;i<array_size;i++){
            if((i+1<array_size) && (arr[i] < arr[i+1])){
                continue;
            } else if((i+1<array_size) && (arr[i] > arr[i+1])){
                if(i!=buy_prefix){
                    sell_prefix = i;
                    printf("(%d %d) ",buy_prefix,sell_prefix);
                    sold=1;
                }
                buy_prefix = i+1;
                
            }
        }
        if(i-1>buy_prefix){
            sell_prefix=i-1;
            sold=1;
            printf("(%d %d)",buy_prefix,sell_prefix);
        }
        if(sold==0){
            printf("No Profit");
            
        }
        if(arr)
           free(arr);
           printf("\n");
   }

    return 0;
}
Ads Blocker Image Powered by Code Help Pro

Ads Blocker Detected!!!

We have detected that you are using extensions to block ads. Please support us by disabling these ads blocker.

Powered By
Best Wordpress Adblock Detecting Plugin | CHP Adblock