129 votes

Bénéfice maximal de la vente unique

Supposons que l'on nous donne un tableau de n des entiers représentant les prix des actions sur un seul jour. Nous voulons trouver une paire (buyDay, sellDay) avec buyDay ≤ sellDay de sorte que si nous avons acheté l'action le buyDay et l'a vendu sur sellDay nous maximiserions notre profit.

Il est clair qu'il y a un O(n 2 ) l'algorithme en essayant toutes les solutions possibles. (buyDay, sellDay) et en prenant le meilleur de chacun d'entre eux. Cependant, existe-t-il un meilleur algorithme, peut-être un qui fonctionne en O(n) temps ?

2 votes

C'est le problème de la sous-séquence à somme maximale avec un niveau d'indirection.

2 votes

@MSN : Comment ça ? Il ne regarde pas du tout les sommes, mais plutôt les différences entre les éléments.

2 votes

@PengOne, Comme je l'ai dit, il y a un niveau d'indirection. Plus précisément, vous voulez maximiser la somme des gains/pertes sur un ensemble contigu de jours. Il faut donc convertir la liste en gains/pertes et trouver la somme maximale des sous-séquences.

305voto

templatetypedef Points 129554

J'adore ce problème. C'est une question d'entretien classique et, selon la façon dont vous l'abordez, vous obtiendrez des solutions de plus en plus intéressantes. Il est certainement possible de faire cela en plus de O(n 2 ), et j'ai énuméré ici trois façons différentes d'envisager le problème. J'espère que cela répond à votre question !

Tout d'abord, la solution "diviser pour mieux régner". Voyons si nous pouvons résoudre ce problème en divisant l'entrée en deux, en résolvant le problème dans chaque sous-réseau, puis en combinant les deux ensemble. Il s'avère que nous pouvons effectivement le faire, et de manière efficace ! L'intuition est la suivante. Si nous n'avons qu'un seul jour, la meilleure option est d'acheter ce jour-là et de revendre le même jour sans faire de profit. Sinon, il faut diviser le tableau en deux moitiés. Si nous réfléchissons à ce que pourrait être la réponse optimale, elle doit se trouver à l'un des trois endroits suivants :

  1. Le couple achat/vente correct se produit entièrement dans la première moitié.
  2. Le couple achat/vente correct se produit entièrement dans la seconde moitié.
  3. La paire correcte d'achat et de vente se produit dans les deux moitiés - nous achetons dans la première moitié, puis nous vendons dans la deuxième moitié.

Nous pouvons obtenir les valeurs de (1) et (2) en invoquant récursivement notre algorithme sur les première et deuxième moitiés. Pour l'option (3), la façon de faire le plus grand profit serait d'acheter au point le plus bas de la première moitié et de vendre au point le plus haut de la deuxième moitié. Nous pouvons trouver les valeurs minimales et maximales dans les deux moitiés en effectuant un simple balayage linéaire sur l'entrée et en trouvant les deux valeurs. Cela nous donne alors un algorithme avec la récurrence suivante :

T(1) <= O(1)
T(n) <= 2T(n / 2) + O(n)

Utilisation de la Théorème du maître pour résoudre la récurrence, nous constatons que cela fonctionne en O(n lg n) temps et utilisera O(lg n) espace pour les appels récursifs. Nous venons de battre le temps naïf de O(n 2 ) solution !

Mais attendez ! Nous pouvons faire beaucoup mieux que cela. Remarquez que la seule raison pour laquelle nous avons un terme O(n) dans notre récurrence est que nous avons dû balayer l'entrée entière en essayant de trouver les valeurs minimum et maximum dans chaque moitié. Puisque nous explorons déjà récursivement chaque moitié, nous pouvons peut-être faire mieux en faisant en sorte que la récursion nous remette également les valeurs minimales et maximales stockées dans chaque moitié ! En d'autres termes, notre récursion renvoie trois choses :

  1. Les moments d'achat et de vente pour maximiser le profit.
  2. La valeur minimale globale dans la gamme.
  3. La valeur maximale globale dans la gamme.

Ces deux dernières valeurs peuvent être calculées récursivement en utilisant une récursion simple que nous pouvons exécuter en même temps que la récursion pour calculer (1) :

  1. Les valeurs max et min d'une plage à un seul élément ne sont que cet élément.
  2. Les valeurs max et min d'une plage à éléments multiples peuvent être trouvées en divisant l'entrée en deux, en trouvant les valeurs max et min de chaque moitié, puis en prenant leurs valeurs max et min respectives.

Si nous utilisons cette approche, notre relation de récurrence est maintenant

T(1) <= O(1)
T(n) <= 2T(n / 2) + O(1)

L'utilisation du théorème du maître ici nous donne un temps d'exécution de O(n) avec O(lg n) d'espace, ce qui est encore mieux que notre solution originale !

Mais attendez une minute - nous pouvons faire encore mieux que cela ! Essayons de résoudre ce problème à l'aide de la programmation dynamique. L'idée sera de penser au problème comme suit. Supposons que nous connaissions la réponse au problème après avoir examiné les k premiers éléments. Pourrions-nous utiliser notre connaissance du (k+1)ème élément, combinée à notre solution initiale, pour résoudre le problème pour les (k+1) premiers éléments ? Si c'est le cas, nous pourrions créer un excellent algorithme en résolvant le problème pour le premier élément, puis les deux premiers, puis les trois premiers, etc. jusqu'à ce que nous l'ayons calculé pour les n premiers éléments.

Réfléchissons à la manière de procéder. Si nous n'avons qu'un seul élément, nous savons déjà qu'il doit s'agir de la meilleure paire achat/vente. Supposons maintenant que nous connaissions la meilleure réponse pour les k premiers éléments et que nous examinions le (k+1)ème élément. La seule façon pour que cette valeur puisse créer une solution meilleure que celle des k premiers éléments est que la différence entre le plus petit des k premiers éléments et ce nouvel élément soit plus grande que la plus grande différence que nous avons calculée jusqu'à présent. Supposons donc qu'au fur et à mesure que nous parcourons les éléments, nous gardons la trace de deux valeurs : la valeur minimale que nous avons vue jusqu'à présent et le bénéfice maximal que nous pourrions réaliser avec les k premiers éléments seulement. Initialement, la valeur minimale que nous avons vue jusqu'à présent est le premier élément, et le bénéfice maximal est zéro. Lorsque nous voyons un nouvel élément, nous mettons d'abord à jour notre profit optimal en calculant combien nous ferions en achetant au prix le plus bas vu jusqu'à présent et en vendant au prix actuel. Si cette valeur est supérieure à la valeur optimale que nous avons calculée jusqu'à présent, nous mettons à jour la solution optimale en fonction de ce nouveau profit. Ensuite, nous mettons à jour l'élément minimum vu jusqu'à présent pour qu'il soit le minimum du plus petit élément actuel et du nouvel élément.

Puisqu'à chaque étape, nous ne faisons que O(1) travail et que nous visitons chacun des n éléments exactement une fois, il faut O(n) temps pour terminer ! De plus, elle n'utilise que O(1) de stockage auxiliaire. C'est le meilleur résultat que nous ayons obtenu jusqu'à présent !

À titre d'exemple, sur vos entrées, voici comment cet algorithme pourrait s'exécuter. Les nombres entre chacune des valeurs du tableau correspondent aux valeurs détenues par l'algorithme à ce moment-là. Vous ne stockerez pas réellement toutes ces valeurs (cela prendrait O(n) de mémoire !), mais il est utile de voir l'algorithme évoluer :

            5        10        4          6         7
min         5         5        4          4         4    
best      (5,5)     (5,10)   (5,10)     (5,10)    (5,10)

Réponse : (5, 10)

            5        10        4          6        12
min         5         5        4          4         4    
best      (5,5)     (5,10)   (5,10)     (5,10)    (4,12)

Réponse : (4, 12)

            1       2       3      4      5
min         1       1       1      1      1
best      (1,1)   (1,2)   (1,3)  (1,4)  (1,5)

Réponse : (1, 5)

Pouvons-nous faire mieux maintenant ? Malheureusement, pas au sens asymptotique du terme. Si nous utilisons un temps inférieur à O(n), nous ne pouvons pas examiner tous les nombres sur de grandes entrées et ne pouvons donc pas garantir que nous ne manquerons pas la réponse optimale (nous pourrions simplement la "cacher" dans les éléments que nous n'avons pas examinés). De plus, nous ne pouvons pas utiliser moins de O(1) d'espace. Il pourrait y avoir quelques optimisations des facteurs constants cachés dans la notation big-O, mais autrement, nous ne pouvons pas nous attendre à trouver des options radicalement meilleures.

Globalement, cela signifie que nous disposons des algorithmes suivants :

  • Naïf : O(n 2 ) temps, O(1) espace.
  • Diviser pour mieux régner : O(n lg n) temps, O(lg n) espace.
  • Diviser et Conquérir optimisé : Temps O(n), espace O(lg n).
  • Programmation dynamique : Temps O(n), espace O(1).

J'espère que cela vous aidera !

EDITAR : Si ça vous intéresse, j'ai codé une version Python de ces quatre algorithmes afin que vous puissiez jouer avec eux et juger de leurs performances relatives. Voici le code :

# Four different algorithms for solving the maximum single-sell profit problem,
# each of which have different time and space complexity.  This is one of my
# all-time favorite algorithms questions, since there are so many different
# answers that you can arrive at by thinking about the problem in slightly
# different ways.
#
# The maximum single-sell profit problem is defined as follows.  You are given
# an array of stock prices representing the value of some stock over time.
# Assuming that you are allowed to buy the stock exactly once and sell the
# stock exactly once, what is the maximum profit you can make?  For example,
# given the prices
#
#                        2, 7, 1, 8, 2, 8, 4, 5, 9, 0, 4, 5
#
# The maximum profit you can make is 8, by buying when the stock price is 1 and
# selling when the stock price is 9.  Note that while the greatest difference
# in the array is 9 (by subtracting 9 - 0), we cannot actually make a profit of
# 9 here because the stock price of 0 comes after the stock price of 9 (though
# if we wanted to lose a lot of money, buying high and selling low would be a
# great idea!)
#
# In the event that there's no profit to be made at all, we can always buy and
# sell on the same date.  For example, given these prices (which might
# represent a buggy-whip manufacturer:)
#
#                            9, 8, 7, 6, 5, 4, 3, 2, 1, 0
#
# The best profit we can make is 0 by buying and selling on the same day.
#
# Let's begin by writing the simplest and easiest algorithm we know of that
# can solve this problem - brute force.  We will just consider all O(n^2) pairs
# of values, and then pick the one with the highest net profit.  There are
# exactly n + (n - 1) + (n - 2) + ... + 1 = n(n + 1)/2 different pairs to pick
# from, so this algorithm will grow quadratically in the worst-case.  However,
# it uses only O(1) memory, which is a somewhat attractive feature.  Plus, if
# our first intuition for the problem gives a quadratic solution, we can be
# satisfied that if we don't come up with anything else, we can always have a
# polynomial-time solution.

def BruteForceSingleSellProfit(arr):
    # Store the best possible profit we can make; initially this is 0.
    bestProfit = 0;

    # Iterate across all pairs and find the best out of all of them.  As a
    # minor optimization, we don't consider any pair consisting of a single
    # element twice, since we already know that we get profit 0 from this.
    for i in range(0, len(arr)):
        for j in range (i + 1, len(arr)):
            bestProfit = max(bestProfit, arr[j] - arr[i])

    return bestProfit

# This solution is extremely inelegant, and it seems like there just *has* to
# be a better solution.  In fact, there are many better solutions, and we'll
# see three of them.
#
# The first insight comes if we try to solve this problem by using a divide-
# and-conquer strategy.  Let's consider what happens if we split the array into
# two (roughly equal) halves.  If we do so, then there are three possible
# options about where the best buy and sell times are:
#
# 1. We should buy and sell purely in the left half of the array.
# 2. We should buy and sell purely in the right half of the array.
# 3. We should buy in the left half of the array and sell in the right half of
#    the array.
#
# (Note that we don't need to consider selling in the left half of the array
# and buying in the right half of the array, since the buy time must always
# come before the sell time)
#
# If we want to solve this problem recursively, then we can get values for (1)
# and (2) by recursively invoking the algorithm on the left and right
# subarrays.  But what about (3)?  Well, if we want to maximize our profit, we
# should be buying at the lowest possible cost in the left half of the array
# and selling at the highest possible cost in the right half of the array.
# This gives a very elegant algorithm for solving this problem:
#
#    If the array has size 0 or size 1, the maximum profit is 0.
#    Otherwise:
#       Split the array in half.
#       Compute the maximum single-sell profit in the left array, call it L.
#       Compute the maximum single-sell profit in the right array, call it R.
#       Find the minimum of the first half of the array, call it Min
#       Find the maximum of the second half of the array, call it Max
#       Return the maximum of L, R, and Max - Min.
#
# Let's consider the time and space complexity of this algorithm.  Our base
# case takes O(1) time, and in our recursive step we make two recursive calls,
# one on each half of the array, and then does O(n) work to scan the array
# elements to find the minimum and maximum values.  This gives the recurrence
#
#    T(1) = O(1)
#    T(n) = 2T(n / 2) + O(n)
#
# Using the Master Theorem, this recurrence solves to O(n log n), which is
# asymptotically faster than our original approach!  However, we do pay a
# (slight) cost in memory usage.  Because we need to maintain space for all of
# the stack frames we use.  Since on each recursive call we cut the array size
# in half, the maximum number of recursive calls we can make is O(log n), so
# this algorithm uses O(n log n) time and O(log n) memory.

def DivideAndConquerSingleSellProfit(arr):
    # Base case: If the array has zero or one elements in it, the maximum
    # profit is 0.
    if len(arr) <= 1:
        return 0;

    # Cut the array into two roughly equal pieces.
    left  = arr[ : len(arr) / 2]
    right = arr[len(arr) / 2 : ]

    # Find the values for buying and selling purely in the left or purely in
    # the right.
    leftBest  = DivideAndConquerSingleSellProfit(left)
    rightBest = DivideAndConquerSingleSellProfit(right)

    # Compute the best profit for buying in the left and selling in the right.
    crossBest = max(right) - min(left)

    # Return the best of the three
    return max(leftBest, rightBest, crossBest)

# While the above algorithm for computing the maximum single-sell profit is
# better timewise than what we started with (O(n log n) versus O(n^2)), we can
# still improve the time performance.  In particular, recall our recurrence
# relation:
#
#    T(1) = O(1)
#    T(n) = 2T(n / 2) + O(n)
#
# Here, the O(n) term in the T(n) case comes from the work being done to find
# the maximum and minimum values in the right and left halves of the array,
# respectively.  If we could find these values faster than what we're doing
# right now, we could potentially decrease the function's runtime.
#
# The key observation here is that we can compute the minimum and maximum
# values of an array using a divide-and-conquer approach.  Specifically:
#
#    If the array has just one element, it is the minimum and maximum value.
#    Otherwise:
#       Split the array in half.
#       Find the minimum and maximum values from the left and right halves.
#       Return the minimum and maximum of these two values.
#
# Notice that our base case does only O(1) work, and our recursive case manages
# to do only O(1) work in addition to the recursive calls.  This gives us the
# recurrence relation
#
#    T(1) = O(1)
#    T(n) = 2T(n / 2) + O(1)
#
# Using the Master Theorem, this solves to O(n).
#
# How can we make use of this result?  Well, in our current divide-and-conquer
# solution, we split the array in half anyway to find the maximum profit we
# could make in the left and right subarrays.  Could we have those recursive
# calls also hand back the maximum and minimum values of the respective arrays?
# If so, we could rewrite our solution as follows:
#
#    If the array has size 1, the maximum profit is zero and the maximum and
#       minimum values are the single array element.
#    Otherwise:
#       Split the array in half.
#       Compute the maximum single-sell profit in the left array, call it L.
#       Compute the maximum single-sell profit in the right array, call it R.
#       Let Min be the minimum value in the left array, which we got from our
#           first recursive call.
#       Let Max be the maximum value in the right array, which we got from our
#           second recursive call.
#       Return the maximum of L, R, and Max - Min for the maximum single-sell
#           profit, and the appropriate maximum and minimum values found from
#           the recursive calls.
#
# The correctness proof for this algorithm works just as it did before, but now
# we never actually do a scan of the array at each step.  In fact, we do only
# O(1) work at each level.  This gives a new recurrence
#
#     T(1) = O(1)
#     T(n) = 2T(n / 2) + O(1)
#
# Which solves to O(n).  We're now using O(n) time and O(log n) memory, which
# is asymptotically faster than before!
#
# The code for this is given below:

def OptimizedDivideAndConquerSingleSellProfit(arr):
    # If the array is empty, the maximum profit is zero.
    if len(arr) == 0:
        return 0

    # This recursive helper function implements the above recurrence.  It
    # returns a triple of (max profit, min array value, max array value).  For
    # efficiency reasons, we always reuse the array and specify the bounds as
    # [lhs, rhs]
    def Recursion(arr, lhs, rhs):
        # If the array has just one element, we return that the profit is zero
        # but the minimum and maximum values are just that array value.
        if lhs == rhs:
            return (0, arr[lhs], arr[rhs])

        # Recursively compute the values for the first and latter half of the
        # array.  To do this, we need to split the array in half.  The line
        # below accomplishes this in a way that, if ported to other languages,
        # cannot result in an integer overflow.
        mid = lhs + (rhs - lhs) / 2

        # Perform the recursion.
        ( leftProfit,  leftMin,  leftMax) = Recursion(arr, lhs, mid)
        (rightProfit, rightMin, rightMax) = Recursion(arr, mid + 1, rhs)

        # Our result is the maximum possible profit, the minimum of the two
        # minima we've found (since the minimum of these two values gives the
        # minimum of the overall array), and the maximum of the two maxima.
        maxProfit = max(leftProfit, rightProfit, rightMax - leftMin)
        return (maxProfit, min(leftMin, rightMin), max(leftMax, rightMax))

    # Using our recursive helper function, compute the resulting value.
    profit, _, _ = Recursion(arr, 0, len(arr) - 1)
    return profit

# At this point we've traded our O(n^2)-time, O(1)-space solution for an O(n)-
# time, O(log n) space solution.  But can we do better than this?
#
# To find a better algorithm, we'll need to switch our line of reasoning.
# Rather than using divide-and-conquer, let's see what happens if we use
# dynamic programming.  In particular, let's think about the following problem.
# If we knew the maximum single-sell profit that we could get in just the first
# k array elements, could we use this information to determine what the
# maximum single-sell profit would be in the first k + 1 array elements?  If we
# could do this, we could use the following algorithm:
#
#   Find the maximum single-sell profit to be made in the first 1 elements.
#   For i = 2 to n:
#      Compute the maximum single-sell profit using the first i elements.
#
# How might we do this?  One intuition is as follows.  Suppose that we know the
# maximum single-sell profit of the first k elements.  If we look at k + 1
# elements, then either the maximum profit we could make by buying and selling
# within the first k elements (in which case nothing changes), or we're
# supposed to sell at the (k + 1)st price.  If we wanted to sell at this price
# for a maximum profit, then we would want to do so by buying at the lowest of
# the first k + 1 prices, then selling at the (k + 1)st price.
#
# To accomplish this, suppose that we keep track of the minimum value in the
# first k elements, along with the maximum profit we could make in the first
# k elements.  Upon seeing the (k + 1)st element, we update what the current
# minimum value is, then update what the maximum profit we can make is by
# seeing whether the difference between the (k + 1)st element and the new
# minimum value is.  Note that it doesn't matter what order we do this in; if
# the (k + 1)st element is the smallest element so far, there's no possible way
# that we could increase our profit by selling at that point.
#
# To finish up this algorithm, we should note that given just the first price,
# the maximum possible profit is 0.
#
# This gives the following simple and elegant algorithm for the maximum single-
# sell profit problem:
#
#   Let profit = 0.
#   Let min = arr[0]
#   For k = 1 to length(arr):
#       If arr[k] < min, set min = arr[k]
#       If profit < arr[k] - min, set profit = arr[k] - min
#
# This is short, sweet, and uses only O(n) time and O(1) memory.  The beauty of
# this solution is that we are quite naturally led there by thinking about how
# to update our answer to the problem in response to seeing some new element.
# In fact, we could consider implementing this algorithm as a streaming
# algorithm, where at each point in time we maintain the maximum possible
# profit and then update our answer every time new data becomes available.
#
# The final version of this algorithm is shown here:

def DynamicProgrammingSingleSellProfit(arr):
    # If the array is empty, we cannot make a profit.
    if len(arr) == 0:
        return 0

    # Otherwise, keep track of the best possible profit and the lowest value
    # seen so far.
    profit = 0
    cheapest = arr[0]

    # Iterate across the array, updating our answer as we go according to the
    # above pseudocode.
    for i in range(1, len(arr)):
        # Update the minimum value to be the lower of the existing minimum and
        # the new minimum.
        cheapest = min(cheapest, arr[i])

        # Update the maximum profit to be the larger of the old profit and the
        # profit made by buying at the lowest value and selling at the current
        # price.
        profit = max(profit, arr[i] - cheapest)

    return profit

# To summarize our algorithms, we have seen
#
# Naive:                        O(n ^ 2)   time, O(1)     space
# Divide-and-conquer:           O(n log n) time, O(log n) space
# Optimized divide-and-conquer: O(n)       time, O(log n) space
# Dynamic programming:          O(n)       time, O(1)     space

1 votes

@FrankQ.- De l'espace est nécessaire pour les deux appels récursifs, mais ces appels sont généralement effectués l'un après l'autre. Cela signifie que le compilateur peut réutiliser la mémoire entre les appels ; une fois qu'un appel revient, l'appel suivant peut réutiliser son espace. Par conséquent, vous n'avez besoin de mémoire que pour contenir un appel de fonction à la fois, de sorte que l'utilisation de la mémoire est proportionnelle à la profondeur maximale de la pile d'appels. Comme la récursion se termine à O(log n) niveaux, seule O(log n) mémoire doit être utilisée. Cela clarifie-t-il les choses ?

0 votes

Quelqu'un pourrait-il les porter en Ruby ? Certaines récursions ne fonctionnent pas de la même manière qu'en Python. De plus, ces solutions ne renvoient que le bénéfice maximal ; elles ne renvoient pas les points du tableau qui ont donné le bénéfice (ce qui pourrait être utilisé pour indiquer le pourcentage d'augmentation du bénéfice dans le passé).

0 votes

Le concept de programmation dynamique n'est pas vraiment nécessaire pour expliquer la solution en temps O(n), mais c'est une bonne chose que vous ayez lié tous ces types d'algorithmes.

32voto

MSN Points 30386

Il s'agit du problème de la sous-séquence de la somme maximale avec un peu d'indirection. Le problème de la sous-séquence de la somme maximale consiste, à partir d'une liste d'entiers qui peuvent être positifs ou négatifs, à trouver la plus grande somme d'un sous-ensemble contigu de cette liste.

Vous pouvez trivialement convertir ce problème en ce problème en prenant le profit ou la perte entre des jours consécutifs. Vous transformeriez donc une liste de prix d'actions, par exemple [5, 6, 7, 4, 2] en une liste de gains/pertes, par exemple, [1, 1, -3, -2] . Le problème de la somme des sous-séquences est alors assez facile à résoudre : Trouver la sous-séquence avec la plus grande somme d'éléments dans un tableau

1 votes

Je ne pense pas que tout à fait C'est ainsi que cela fonctionne, car si vous achetez l'action un jour initial, vous ne bénéficiez pas des avantages du delta du jour précédent. Ou bien cela ne pose-t-il pas de problème dans cette approche ?

1 votes

@templateetypedef, c'est pourquoi vous suivez la plus grande somme et la somme de la séquence actuelle. Lorsque la somme de la séquence actuelle passe en dessous de zéro, vous savez que vous n'aurez pas gagné d'argent avec cette séquence et que vous pouvez recommencer. En suivant la plus grande somme, vous trouverez automatiquement les meilleures dates d'achat/de vente.

6 votes

@templateetypedef, d'ailleurs, vous faites la même chose dans votre réponse.

3voto

Ajeet Points 1642

KeithSchartz a donné une réponse étonnante et il a codé en python toutes les algos. Mais ma seule inquiétude (à long terme) est qu'après 30 ou 40 ans, il pourrait cesser de payer pour son domaine et nous perdrions ses réponses. Je pense qu'il est préférable d'accrocher ces réponses à SO afin qu'elles soient préservées avec une plus grande probabilité :)

http://keithschwarz.com/
http://keithschwarz.com/interesting/code/?dir=single-sell-profit

 # File: SingleSellProfit.py
# Author: Keith Schwarz (htiek@cs.stanford.edu)
#
# Four different algorithms for solving the maximum single-sell profit problem,
# each of which have different time and space complexity.  This is one of my
# all-time favorite algorithms questions, since there are so many different
# answers that you can arrive at by thinking about the problem in slightly
# different ways.
#
# The maximum single-sell profit problem is defined as follows.  You are given
# an array of stock prices representing the value of some stock over time.
# Assuming that you are allowed to buy the stock exactly once and sell the
# stock exactly once, what is the maximum profit you can make?  For example,
# given the prices
#
#                        2, 7, 1, 8, 2, 8, 4, 5, 9, 0, 4, 5
#
# The maximum profit you can make is 8, by buying when the stock price is 1 and
# selling when the stock price is 9.  Note that while the greatest difference
# in the array is 9 (by subtracting 9 - 0), we cannot actually make a profit of
# 9 here because the stock price of 0 comes after the stock price of 9 (though
# if we wanted to lose a lot of money, buying high and selling low would be a
# great idea!)
#
# In the event that there's no profit to be made at all, we can always buy and
# sell on the same date.  For example, given these prices (which might
# represent a buggy-whip manufacturer:)
#
#                            9, 8, 7, 6, 5, 4, 3, 2, 1, 0
#
# The best profit we can make is 0 by buying and selling on the same day.
#
# Let's begin by writing the simplest and easiest algorithm we know of that
# can solve this problem - brute force.  We will just consider all O(n^2) pairs
# of values, and then pick the one with the highest net profit.  There are
# exactly n + (n - 1) + (n - 2) + ... + 1 = n(n + 1)/2 different pairs to pick
# from, so this algorithm will grow quadratically in the worst-case.  However,
# it uses only O(1) memory, which is a somewhat attractive feature.  Plus, if
# our first intuition for the problem gives a quadratic solution, we can be
# satisfied that if we don't come up with anything else, we can always have a
# polynomial-time solution.

def BruteForceSingleSellProfit(arr):
    # Store the best possible profit we can make; initially this is 0.
    bestProfit = 0;

    # Iterate across all pairs and find the best out of all of them.  As a
    # minor optimization, we don't consider any pair consisting of a single
    # element twice, since we already know that we get profit 0 from this.
    for i in range(0, len(arr)):
        for j in range (i + 1, len(arr)):
            bestProfit = max(bestProfit, arr[j] - arr[i])

    return bestProfit

# This solution is extremely inelegant, and it seems like there just *has* to
# be a better solution.  In fact, there are many better solutions, and we'll
# see three of them.
#
# The first insight comes if we try to solve this problem by using a divide-
# and-conquer strategy.  Let's consider what happens if we split the array into
# two (roughly equal) halves.  If we do so, then there are three possible
# options about where the best buy and sell times are:
#
# 1. We should buy and sell purely in the left half of the array.
# 2. We should buy and sell purely in the right half of the array.
# 3. We should buy in the left half of the array and sell in the right half of
#    the array.
#
# (Note that we don't need to consider selling in the left half of the array
# and buying in the right half of the array, since the buy time must always
# come before the sell time)
#
# If we want to solve this problem recursively, then we can get values for (1)
# and (2) by recursively invoking the algorithm on the left and right
# subarrays.  But what about (3)?  Well, if we want to maximize our profit, we
# should be buying at the lowest possible cost in the left half of the array
# and selling at the highest possible cost in the right half of the array.
# This gives a very elegant algorithm for solving this problem:
#
#    If the array has size 0 or size 1, the maximum profit is 0.
#    Otherwise:
#       Split the array in half.
#       Compute the maximum single-sell profit in the left array, call it L.
#       Compute the maximum single-sell profit in the right array, call it R.
#       Find the minimum of the first half of the array, call it Min
#       Find the maximum of the second half of the array, call it Max
#       Return the maximum of L, R, and Max - Min.
#
# Let's consider the time and space complexity of this algorithm.  Our base
# case takes O(1) time, and in our recursive step we make two recursive calls,
# one on each half of the array, and then does O(n) work to scan the array
# elements to find the minimum and maximum values.  This gives the recurrence
#
#    T(1)     = O(1)
#    T(n / 2) = 2T(n / 2) + O(n)
#
# Using the Master Theorem, this recurrence solves to O(n log n), which is
# asymptotically faster than our original approach!  However, we do pay a
# (slight) cost in memory usage.  Because we need to maintain space for all of
# the stack frames we use.  Since on each recursive call we cut the array size
# in half, the maximum number of recursive calls we can make is O(log n), so
# this algorithm uses O(n log n) time and O(log n) memory.

def DivideAndConquerSingleSellProfit(arr):
    # Base case: If the array has zero or one elements in it, the maximum
    # profit is 0.
    if len(arr) <= 1:
        return 0;

    # Cut the array into two roughly equal pieces.
    left  = arr[ : len(arr) / 2]
    right = arr[len(arr) / 2 : ]

    # Find the values for buying and selling purely in the left or purely in
    # the right.
    leftBest  = DivideAndConquerSingleSellProfit(left)
    rightBest = DivideAndConquerSingleSellProfit(right)

    # Compute the best profit for buying in the left and selling in the right.
    crossBest = max(right) - min(left)

    # Return the best of the three
    return max(leftBest, rightBest, crossBest)

# While the above algorithm for computing the maximum single-sell profit is
# better timewise than what we started with (O(n log n) versus O(n^2)), we can
# still improve the time performance.  In particular, recall our recurrence
# relation:
#
#    T(1) = O(1)
#    T(n) = 2T(n / 2) + O(n)
#
# Here, the O(n) term in the T(n) case comes from the work being done to find
# the maximum and minimum values in the right and left halves of the array,
# respectively.  If we could find these values faster than what we're doing
# right now, we could potentially decrease the function's runtime.
#
# The key observation here is that we can compute the minimum and maximum
# values of an array using a divide-and-conquer approach.  Specifically:
#
#    If the array has just one element, it is the minimum and maximum value.
#    Otherwise:
#       Split the array in half.
#       Find the minimum and maximum values from the left and right halves.
#       Return the minimum and maximum of these two values.
#
# Notice that our base case does only O(1) work, and our recursive case manages
# to do only O(1) work in addition to the recursive calls.  This gives us the
# recurrence relation
#
#    T(1) = O(1)
#    T(n) = 2T(n / 2) + O(1)
#
# Using the Master Theorem, this solves to O(n).
#
# How can we make use of this result?  Well, in our current divide-and-conquer
# solution, we split the array in half anyway to find the maximum profit we
# could make in the left and right subarrays.  Could we have those recursive
# calls also hand back the maximum and minimum values of the respective arrays?
# If so, we could rewrite our solution as follows:
#
#    If the array has size 1, the maximum profit is zero and the maximum and
#       minimum values are the single array element.
#    Otherwise:
#       Split the array in half.
#       Compute the maximum single-sell profit in the left array, call it L.
#       Compute the maximum single-sell profit in the right array, call it R.
#       Let Min be the minimum value in the left array, which we got from our
#           first recursive call.
#       Let Max be the maximum value in the right array, which we got from our
#           second recursive call.
#       Return the maximum of L, R, and Max - Min for the maximum single-sell
#           profit, and the appropriate maximum and minimum values found from
#           the recursive calls.
#
# The correctness proof for this algorithm works just as it did before, but now
# we never actually do a scan of the array at each step.  In fact, we do only
# O(1) work at each level.  This gives a new recurrence
#
#     T(1) = O(1)
#     T(n) = 2T(n / 2) + O(1)
#
# Which solves to O(n).  We're now using O(n) time and O(log n) memory, which
# is asymptotically faster than before!
#
# The code for this is given below:

def OptimizedDivideAndConquerSingleSellProfit(arr):
    # If the array is empty, the maximum profit is zero.
    if len(arr) == 0:
        return 0

    # This recursive helper function implements the above recurrence.  It
    # returns a triple of (max profit, min array value, max array value).  For
    # efficiency reasons, we always reuse the array and specify the bounds as
    # [lhs, rhs]
    def Recursion(arr, lhs, rhs):
        # If the array has just one element, we return that the profit is zero
        # but the minimum and maximum values are just that array value.
        if lhs == rhs:
            return (0, arr[lhs], arr[rhs])

        # Recursively compute the values for the first and latter half of the
        # array.  To do this, we need to split the array in half.  The line
        # below accomplishes this in a way that, if ported to other languages,
        # cannot result in an integer overflow.
        mid = lhs + (rhs - lhs) / 2

        # Perform the recursion.
        ( leftProfit,  leftMin,  leftMax) = Recursion(arr, lhs, mid)
        (rightProfit, rightMin, rightMax) = Recursion(arr, mid + 1, rhs)

        # Our result is the maximum possible profit, the minimum of the two
        # minima we've found (since the minimum of these two values gives the
        # minimum of the overall array), and the maximum of the two maxima.
        maxProfit = max(leftProfit, rightProfit, rightMax - leftMin)
        return (maxProfit, min(leftMin, rightMin), max(leftMax, rightMax))

    # Using our recursive helper function, compute the resulting value.
    profit, _, _ = Recursion(arr, 0, len(arr) - 1)
    return profit

# At this point we've traded our O(n^2)-time, O(1)-space solution for an O(n)-
# time, O(log n) space solution.  But can we do better than this?
#
# To find a better algorithm, we'll need to switch our line of reasoning.
# Rather than using divide-and-conquer, let's see what happens if we use
# dynamic programming.  In particular, let's think about the following problem.
# If we knew the maximum single-sell profit that we could get in just the first
# k array elements, could we use this information to determine what the
# maximum single-sell profit would be in the first k + 1 array elements?  If we
# could do this, we could use the following algorithm:
#
#   Find the maximum single-sell profit to be made in the first 1 elements.
#   For i = 2 to n:
#      Compute the maximum single-sell profit using the first i elements.
#
# How might we do this?  One intuition is as follows.  Suppose that we know the
# maximum single-sell profit of the first k elements.  If we look at k + 1
# elements, then either the maximum profit we could make by buying and selling
# within the first k elements (in which case nothing changes), or we're
# supposed to sell at the (k + 1)st price.  If we wanted to sell at this price
# for a maximum profit, then we would want to do so by buying at the lowest of
# the first k + 1 prices, then selling at the (k + 1)st price.
#
# To accomplish this, suppose that we keep track of the minimum value in the
# first k elements, along with the maximum profit we could make in the first
# k elements.  Upon seeing the (k + 1)st element, we update what the current
# minimum value is, then update what the maximum profit we can make is by
# seeing whether the difference between the (k + 1)st element and the new
# minimum value is.  Note that it doesn't matter what order we do this in; if
# the (k + 1)st element is the smallest element so far, there's no possible way
# that we could increase our profit by selling at that point.
#
# To finish up this algorithm, we should note that given just the first price,
# the maximum possible profit is 0.
#
# This gives the following simple and elegant algorithm for the maximum single-
# sell profit problem:
#
#   Let profit = 0.
#   Let min = arr[0]
#   For k = 1 to length(arr):
#       If arr[k] < min, set min = arr[k]
#       If profit < arr[k] - min, set profit = arr[k] - min
#
# This is short, sweet, and uses only O(n) time and O(1) memory.  The beauty of
# this solution is that we are quite naturally led there by thinking about how
# to update our answer to the problem in response to seeing some new element.
# In fact, we could consider implementing this algorithm as a streaming
# algorithm, where at each point in time we maintain the maximum possible
# profit and then update our answer every time new data becomes available.
#
# The final version of this algorithm is shown here:

def DynamicProgrammingSingleSellProfit(arr):
    # If the array is empty, we cannot make a profit.
    if len(arr) == 0:
        return 0

    # Otherwise, keep track of the best possible profit and the lowest value
    # seen so far.
    profit = 0
    cheapest = arr[0]

    # Iterate across the array, updating our answer as we go according to the
    # above pseudocode.
    for i in range(1, len(arr)):
        # Update the minimum value to be the lower of the existing minimum and
        # the new minimum.
        cheapest = min(cheapest, arr[i])

        # Update the maximum profit to be the larger of the old profit and the
        # profit made by buying at the lowest value and selling at the current
        # price.
        profit = max(profit, arr[i] - cheapest)

    return profit

# To summarize our algorithms, we have seen
#
# Naive:                        O(n ^ 2)   time, O(1)     space
# Divide-and-conquer:           O(n log n) time, O(log n) space
# Optimized divide-and-conquer: O(n)       time, O(log n) space
# Dynamic programming:          O(n)       time, O(1)     space

2voto

Voici ma solution Java :

public static void main(String[] args) {
    int A[] = {5,10,4,6,12};

    int min = A[0]; // Lets assume first element is minimum
    int maxProfit = 0; // 0 profit, if we buy & sell on same day.
    int profit = 0;
    int minIndex = 0; // Index of buy date
    int maxIndex = 0; // Index of sell date

    //Run the loop from next element
    for (int i = 1; i < A.length; i++) {
        //Keep track of minimum buy price & index
        if (A[i] < min) {
            min = A[i];
            minIndex = i;
        }
        profit = A[i] - min;
        //If new profit is more than previous profit, keep it and update the max index
        if (profit > maxProfit) {
            maxProfit = profit;
            maxIndex = i;
        }
    }
    System.out.println("maxProfit is "+maxProfit);
    System.out.println("minIndex is "+minIndex);
    System.out.println("maxIndex is "+maxIndex);     
}

0 votes

@Nitiraj , oui cette solution est correcte mais je vous demanderais de lire la réponse fournie par templatetypedef, car dans la réponse fournie par templatetypedef, toutes les solutions possibles sont mentionnées y compris celle postée par Rohit. La solution de Rohit est en fait une implémentation de la dernière solution avec O(n) en utilisant la programmation dynamique mentionnée dans la réponse fournie par templatetypedef.

1 votes

Supposons que votre tableau est int A[] = {5, 4, 6 ,7 ,6 ,3 ,2, 5} ; Alors selon votre logique vous allez acheter à l'indice 6 et ensuite le vendre à l'indice 3. Ce qui est faux. Vous ne pouvez pas vendre dans le passé. L'indice de vente doit être supérieur à l'indice d'achat.

1 votes

La solution ci-dessus est "presque" correcte, mais elle imprime l'indice min absolu au lieu de l'indice du prix d'achat. Pour corriger, vous avez besoin d'une autre variable, disons minBuyIndex, que vous mettez à jour uniquement dans le bloc "if (profit > maxProfit)" et que vous imprimez.

2voto

Vikas Choudhary Points 271

Le problème est identique à la sous-séquence maximale
Je l'ai résolu en utilisant la programmation dynamique. Gardez la trace du courant et du précédent (Profit, date d'achat et date de vente). Si le courant est supérieur au précédent, remplacez le précédent par le courant.

    int prices[] = { 38, 37, 35, 31, 20, 24, 35, 21, 24, 21, 23, 20, 23, 25, 27 };

    int buyDate = 0, tempbuyDate = 0;
    int sellDate = 0, tempsellDate = 0; 

    int profit = 0, tempProfit =0;
    int i ,x = prices.length;
    int previousDayPrice = prices[0], currentDayprice=0;

    for(i=1 ; i<x; i++ ) {

        currentDayprice = prices[i];

        if(currentDayprice > previousDayPrice ) {  // price went up

            tempProfit = tempProfit + currentDayprice - previousDayPrice;
            tempsellDate = i;
        }
        else { // price went down 

            if(tempProfit>profit) { // check if the current Profit is higher than previous profit....

                profit = tempProfit;
                sellDate = tempsellDate;
                buyDate = tempbuyDate;
            } 
                                     // re-intialized buy&sell date, profit....
                tempsellDate = i;
                tempbuyDate = i;
                tempProfit =0;
        }
        previousDayPrice = currentDayprice;
    }

    // if the profit is highest till the last date....
    if(tempProfit>profit) {
        System.out.println("buydate " + tempbuyDate + " selldate " + tempsellDate + " profit " + tempProfit );
    }
    else {
        System.out.println("buydate " + buyDate + " selldate " + sellDate + " profit " + profit );
    }

Prograide.com

Prograide est une communauté de développeurs qui cherche à élargir la connaissance de la programmation au-delà de l'anglais.
Pour cela nous avons les plus grands doutes résolus en français et vous pouvez aussi poser vos propres questions ou résoudre celles des autres.

Powered by:

X