Stock Maximize


Problem Statement :


Your algorithms have become so good at predicting the market that you now know what the share price of Wooden Orange Toothpicks Inc. (WOT) will be for the next number of days.

Each day, you can either buy one share of WOT, sell any number of shares of WOT that you own, or not make any transaction at all. What is the maximum profit you can obtain with an optimum trading strategy?

Example
prices = [1,2]
Buy one share day one, and sell it day two for a profit of 1. Return 1.
prices = [2,1]
No profit can be made so you do not buy or sell stock those days. Return 0.

Function Description

Complete the stockmax function in the editor below.

stockmax has the following parameter(s):

prices: an array of integers that represent predicted daily stock prices
Returns

int: the maximum profit achievable
Input Format

The first line contains the number of test cases t.

Each of the next t pairs of lines contain:
- The first line contains an integer n, the number of predicted prices for WOT.
- The next line contains n space-separated integers prices[i], each a predicted stock price for day i.

Constraints
1 <= t <= 10
1 <= n <= 5000
1 <= prices[i]  <= 100000

Output Format

Output t lines, each containing the maximum profit which can be obtained for the corresponding test case.



Solution :



title-img


                            Solution in C :

In C++ :






#include<bits/stdc++.h>
using namespace std;
int main()
{
	int t;
	scanf("%d",&t);
	while(t--)
	{
		long long int n,a[50005],i,idx,b[50005],sum=0;
		scanf("%lld",&n);
		for(i=1;i<=n;i++)
		{
			scanf("%lld",&a[i]);
		}
		idx=n;
		b[n]=n;
		for(i=n-1;i>0;i--)
		{
			if(a[idx]<a[i])
			idx=i;
			b[i]=idx;
		}
		for(i=1;i<=n;i++)
		{
			if((a[b[i]]-a[i])>=0)
			sum+=(a[b[i]]-a[i]);
		}
		cout<<sum<<endl;
	}
}








In Java :





import java.util.Scanner;

public class Solution {

    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        int T = input.nextInt();
        for (int t=0; t<T; t++) {
            int N = input.nextInt();
            int[] A = new int[N];
            for (int n=0; n<N; n++) {
                A[n] = input.nextInt();
            }
            boolean[] buy = new boolean[N];
            int max = A[N-1];
            for (int n=N-2; n>=0; n--) {
                int value = A[n];
                if (value > max) {
                    max = value;
                } else {
                    buy[n] = true;
                }
            }
            long money = 0;
            long stock = 0;
            for (int n=0; n<N; n++) {
                if (buy[n]) {
                    money -= A[n];
                    stock++;
                } else {
                    money += stock*A[n];
                    stock = 0;
                }
            }
            System.out.println(money);
        }
    }
    
}








In C :





#include<stdio.h>
int maxarray(int *a,int start,int end)
{
    int i,pos,big;
    big=a[start];
    pos=start;
    for(i=start;i<=end;i++)
    {
        if(a[i]>big)
        {
        pos=i;
        big=a[i];
        }
    }
    return pos;
}
int main()
{
    int t,n,i;
    scanf("%d",&t);
    while(t--)
    {
        long long pro=0;
        int pos=0,start=0;
        scanf("%d",&n);
        int a[n];
        for(i=0;i<n;i++)
        {
            scanf("%d",&a[i]);
        }
        while(pos!=(n-1))
        {
        pos=maxarray(a,start,n-1);
        for(i=start;i<pos;i++)
        {
            pro=pro+(a[pos]-a[i]);
        }
        start=pos+1;
        }
        printf("%lld\n",pro);
    }
    return 0;
}








In Python3 :





test=int(input())
for i in range(test):
    n=int(input())
    a=list(map(int,input().split()))
    c=0
    i=len(a)-1
    while(i>=0):
        d=a[i]
        l=i
        p=0
        while(a[i]<=d and i>=0):
            p+=a[i]
            i-=1
        c+=(l-i)*a[l]-p
        continue
    print (c)
                        








View More Similar Problems

Get Node Value

This challenge is part of a tutorial track by MyCodeSchool Given a pointer to the head of a linked list and a specific position, determine the data value at that position. Count backwards from the tail node. The tail is at postion 0, its parent is at 1 and so on. Example head refers to 3 -> 2 -> 1 -> 0 -> NULL positionFromTail = 2 Each of the data values matches its distance from the t

View Solution →

Delete duplicate-value nodes from a sorted linked list

This challenge is part of a tutorial track by MyCodeSchool You are given the pointer to the head node of a sorted linked list, where the data in the nodes is in ascending order. Delete nodes and return a sorted list with each distinct value in the original list. The given head pointer may be null indicating that the list is empty. Example head refers to the first node in the list 1 -> 2 -

View Solution →

Cycle Detection

A linked list is said to contain a cycle if any node is visited more than once while traversing the list. Given a pointer to the head of a linked list, determine if it contains a cycle. If it does, return 1. Otherwise, return 0. Example head refers 1 -> 2 -> 3 -> NUL The numbers shown are the node numbers, not their data values. There is no cycle in this list so return 0. head refer

View Solution →

Find Merge Point of Two Lists

This challenge is part of a tutorial track by MyCodeSchool Given pointers to the head nodes of 2 linked lists that merge together at some point, find the node where the two lists merge. The merge point is where both lists point to the same node, i.e. they reference the same memory location. It is guaranteed that the two head nodes will be different, and neither will be NULL. If the lists share

View Solution →

Inserting a Node Into a Sorted Doubly Linked List

Given a reference to the head of a doubly-linked list and an integer ,data , create a new DoublyLinkedListNode object having data value data and insert it at the proper location to maintain the sort. Example head refers to the list 1 <-> 2 <-> 4 - > NULL. data = 3 Return a reference to the new list: 1 <-> 2 <-> 4 - > NULL , Function Description Complete the sortedInsert function

View Solution →

Reverse a doubly linked list

This challenge is part of a tutorial track by MyCodeSchool Given the pointer to the head node of a doubly linked list, reverse the order of the nodes in place. That is, change the next and prev pointers of the nodes so that the direction of the list is reversed. Return a reference to the head node of the reversed list. Note: The head node might be NULL to indicate that the list is empty.

View Solution →