Buy and Sell a Stock for maximum profit (given a day and a price)

The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP





.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty margin-bottom:0;







up vote
2
down vote

favorite












If you were only permitted to complete at most one transaction (i.e., buy one and sell one share of the stock), design an algorithm to find the maximum profit.



Example one:
Input: [7,1,5,3,6,4]
Output: 5
Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5. Not 7-1 = 6, as selling price needs to be larger than buying price.



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



My solution:



walked the array grabbing the initial price and continued to swap it with the smallest value. Between the current smallest value < and only the proceeding larger peaks. With the solution being the largest chasms (difference) between the lowest peak and highest summit in value within an interval. TimeComplexity is O(n) space complexity is O(1) only using one object.






const perfectPrice = (prices, peak = 
buy: null,
buy_day: null,
sell_day: null,
sell: null,
profit: 0,
profitable:
) =>


console.log("(test 1):", perfectPrice([7, 1, 5, 3, 6, 4]))
console.log("(test 2):", perfectPrice([7, 6, 4, 3, 1]))
console.log("(test 3):", perfectPrice([7, 1, 5, 3, 6, 4]))
console.log("(test 4):", perfectPrice([1, 2]))
console.log("(test 5):", perfectPrice([7, 1, 5, 3, 6, 4]))
console.log("(test 6):", perfectPrice([2, 9, 5, 3, 1, 4]))

.as-console-wrapper 
max-height: 100% !important;
top: 0;









share|improve this question

















  • 1




    Still looks broken as there are only two days in test case 4, yet Monday and Wednesday aren't one night apart.
    – Gerrit0
    Aug 1 at 2:37










  • @Gerrit0 added days of the week last min forgot to remove the offset. fixed. thanks for pointing that out.
    – Rick
    Aug 1 at 2:45






  • 1




    I think this is not working correctly. Take this test case: [2, 9, 5, 3, 1, 4] . It should say: buy on Monday, sell on Tuesday, get 7. But instead it says: buy on Friday, sell on Tuesday, get 7. Where the amount looks correct but not the day.
    – insertusernamehere
    Aug 1 at 13:25











  • @insertusernamehere thanks for pointing that out. Where I was collecting the days and prices were incorrect. I needed to collect them only in the profitability section. thanks for pointing that out.
    – Rick
    Aug 1 at 17:19
















up vote
2
down vote

favorite












If you were only permitted to complete at most one transaction (i.e., buy one and sell one share of the stock), design an algorithm to find the maximum profit.



Example one:
Input: [7,1,5,3,6,4]
Output: 5
Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5. Not 7-1 = 6, as selling price needs to be larger than buying price.



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



My solution:



walked the array grabbing the initial price and continued to swap it with the smallest value. Between the current smallest value < and only the proceeding larger peaks. With the solution being the largest chasms (difference) between the lowest peak and highest summit in value within an interval. TimeComplexity is O(n) space complexity is O(1) only using one object.






const perfectPrice = (prices, peak = 
buy: null,
buy_day: null,
sell_day: null,
sell: null,
profit: 0,
profitable:
) =>


console.log("(test 1):", perfectPrice([7, 1, 5, 3, 6, 4]))
console.log("(test 2):", perfectPrice([7, 6, 4, 3, 1]))
console.log("(test 3):", perfectPrice([7, 1, 5, 3, 6, 4]))
console.log("(test 4):", perfectPrice([1, 2]))
console.log("(test 5):", perfectPrice([7, 1, 5, 3, 6, 4]))
console.log("(test 6):", perfectPrice([2, 9, 5, 3, 1, 4]))

.as-console-wrapper 
max-height: 100% !important;
top: 0;









share|improve this question

















  • 1




    Still looks broken as there are only two days in test case 4, yet Monday and Wednesday aren't one night apart.
    – Gerrit0
    Aug 1 at 2:37










  • @Gerrit0 added days of the week last min forgot to remove the offset. fixed. thanks for pointing that out.
    – Rick
    Aug 1 at 2:45






  • 1




    I think this is not working correctly. Take this test case: [2, 9, 5, 3, 1, 4] . It should say: buy on Monday, sell on Tuesday, get 7. But instead it says: buy on Friday, sell on Tuesday, get 7. Where the amount looks correct but not the day.
    – insertusernamehere
    Aug 1 at 13:25











  • @insertusernamehere thanks for pointing that out. Where I was collecting the days and prices were incorrect. I needed to collect them only in the profitability section. thanks for pointing that out.
    – Rick
    Aug 1 at 17:19












up vote
2
down vote

favorite









up vote
2
down vote

favorite











If you were only permitted to complete at most one transaction (i.e., buy one and sell one share of the stock), design an algorithm to find the maximum profit.



Example one:
Input: [7,1,5,3,6,4]
Output: 5
Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5. Not 7-1 = 6, as selling price needs to be larger than buying price.



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



My solution:



walked the array grabbing the initial price and continued to swap it with the smallest value. Between the current smallest value < and only the proceeding larger peaks. With the solution being the largest chasms (difference) between the lowest peak and highest summit in value within an interval. TimeComplexity is O(n) space complexity is O(1) only using one object.






const perfectPrice = (prices, peak = 
buy: null,
buy_day: null,
sell_day: null,
sell: null,
profit: 0,
profitable:
) =>


console.log("(test 1):", perfectPrice([7, 1, 5, 3, 6, 4]))
console.log("(test 2):", perfectPrice([7, 6, 4, 3, 1]))
console.log("(test 3):", perfectPrice([7, 1, 5, 3, 6, 4]))
console.log("(test 4):", perfectPrice([1, 2]))
console.log("(test 5):", perfectPrice([7, 1, 5, 3, 6, 4]))
console.log("(test 6):", perfectPrice([2, 9, 5, 3, 1, 4]))

.as-console-wrapper 
max-height: 100% !important;
top: 0;









share|improve this question













If you were only permitted to complete at most one transaction (i.e., buy one and sell one share of the stock), design an algorithm to find the maximum profit.



Example one:
Input: [7,1,5,3,6,4]
Output: 5
Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5. Not 7-1 = 6, as selling price needs to be larger than buying price.



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



My solution:



walked the array grabbing the initial price and continued to swap it with the smallest value. Between the current smallest value < and only the proceeding larger peaks. With the solution being the largest chasms (difference) between the lowest peak and highest summit in value within an interval. TimeComplexity is O(n) space complexity is O(1) only using one object.






const perfectPrice = (prices, peak = 
buy: null,
buy_day: null,
sell_day: null,
sell: null,
profit: 0,
profitable:
) =>


console.log("(test 1):", perfectPrice([7, 1, 5, 3, 6, 4]))
console.log("(test 2):", perfectPrice([7, 6, 4, 3, 1]))
console.log("(test 3):", perfectPrice([7, 1, 5, 3, 6, 4]))
console.log("(test 4):", perfectPrice([1, 2]))
console.log("(test 5):", perfectPrice([7, 1, 5, 3, 6, 4]))
console.log("(test 6):", perfectPrice([2, 9, 5, 3, 1, 4]))

.as-console-wrapper 
max-height: 100% !important;
top: 0;








const perfectPrice = (prices, peak = 
buy: null,
buy_day: null,
sell_day: null,
sell: null,
profit: 0,
profitable:
) =>


console.log("(test 1):", perfectPrice([7, 1, 5, 3, 6, 4]))
console.log("(test 2):", perfectPrice([7, 6, 4, 3, 1]))
console.log("(test 3):", perfectPrice([7, 1, 5, 3, 6, 4]))
console.log("(test 4):", perfectPrice([1, 2]))
console.log("(test 5):", perfectPrice([7, 1, 5, 3, 6, 4]))
console.log("(test 6):", perfectPrice([2, 9, 5, 3, 1, 4]))

.as-console-wrapper 
max-height: 100% !important;
top: 0;





const perfectPrice = (prices, peak = 
buy: null,
buy_day: null,
sell_day: null,
sell: null,
profit: 0,
profitable:
) =>


console.log("(test 1):", perfectPrice([7, 1, 5, 3, 6, 4]))
console.log("(test 2):", perfectPrice([7, 6, 4, 3, 1]))
console.log("(test 3):", perfectPrice([7, 1, 5, 3, 6, 4]))
console.log("(test 4):", perfectPrice([1, 2]))
console.log("(test 5):", perfectPrice([7, 1, 5, 3, 6, 4]))
console.log("(test 6):", perfectPrice([2, 9, 5, 3, 1, 4]))

.as-console-wrapper 
max-height: 100% !important;
top: 0;








share|improve this question












share|improve this question




share|improve this question








edited Aug 1 at 17:16
























asked Aug 1 at 1:44









Rick

22819




22819







  • 1




    Still looks broken as there are only two days in test case 4, yet Monday and Wednesday aren't one night apart.
    – Gerrit0
    Aug 1 at 2:37










  • @Gerrit0 added days of the week last min forgot to remove the offset. fixed. thanks for pointing that out.
    – Rick
    Aug 1 at 2:45






  • 1




    I think this is not working correctly. Take this test case: [2, 9, 5, 3, 1, 4] . It should say: buy on Monday, sell on Tuesday, get 7. But instead it says: buy on Friday, sell on Tuesday, get 7. Where the amount looks correct but not the day.
    – insertusernamehere
    Aug 1 at 13:25











  • @insertusernamehere thanks for pointing that out. Where I was collecting the days and prices were incorrect. I needed to collect them only in the profitability section. thanks for pointing that out.
    – Rick
    Aug 1 at 17:19












  • 1




    Still looks broken as there are only two days in test case 4, yet Monday and Wednesday aren't one night apart.
    – Gerrit0
    Aug 1 at 2:37










  • @Gerrit0 added days of the week last min forgot to remove the offset. fixed. thanks for pointing that out.
    – Rick
    Aug 1 at 2:45






  • 1




    I think this is not working correctly. Take this test case: [2, 9, 5, 3, 1, 4] . It should say: buy on Monday, sell on Tuesday, get 7. But instead it says: buy on Friday, sell on Tuesday, get 7. Where the amount looks correct but not the day.
    – insertusernamehere
    Aug 1 at 13:25











  • @insertusernamehere thanks for pointing that out. Where I was collecting the days and prices were incorrect. I needed to collect them only in the profitability section. thanks for pointing that out.
    – Rick
    Aug 1 at 17:19







1




1




Still looks broken as there are only two days in test case 4, yet Monday and Wednesday aren't one night apart.
– Gerrit0
Aug 1 at 2:37




Still looks broken as there are only two days in test case 4, yet Monday and Wednesday aren't one night apart.
– Gerrit0
Aug 1 at 2:37












@Gerrit0 added days of the week last min forgot to remove the offset. fixed. thanks for pointing that out.
– Rick
Aug 1 at 2:45




@Gerrit0 added days of the week last min forgot to remove the offset. fixed. thanks for pointing that out.
– Rick
Aug 1 at 2:45




1




1




I think this is not working correctly. Take this test case: [2, 9, 5, 3, 1, 4] . It should say: buy on Monday, sell on Tuesday, get 7. But instead it says: buy on Friday, sell on Tuesday, get 7. Where the amount looks correct but not the day.
– insertusernamehere
Aug 1 at 13:25





I think this is not working correctly. Take this test case: [2, 9, 5, 3, 1, 4] . It should say: buy on Monday, sell on Tuesday, get 7. But instead it says: buy on Friday, sell on Tuesday, get 7. Where the amount looks correct but not the day.
– insertusernamehere
Aug 1 at 13:25













@insertusernamehere thanks for pointing that out. Where I was collecting the days and prices were incorrect. I needed to collect them only in the profitability section. thanks for pointing that out.
– Rick
Aug 1 at 17:19




@insertusernamehere thanks for pointing that out. Where I was collecting the days and prices were incorrect. I needed to collect them only in the profitability section. thanks for pointing that out.
– Rick
Aug 1 at 17:19










1 Answer
1






active

oldest

votes

















up vote
0
down vote













Readability



  • The way you've named your variables makes the code more difficult to read for example peak just doesn't make sense to me. Another consideration would be to rename buy_day to cheapest_day

  • Don't overcomplicate things: I found the return statement at the end of your forEach confusing

General syntax improvement that would make the code easier to read:



  • Use camelCase over snake_case

  • Use dot notation when accessing an objects properties where possible

Remove unnecessary/unused code



  • You have an if/elseif that does the same thing this can be simplified using an or statement if (this || that)


  • peak.sell and peak.sell_day are never used, same for all in your prices.forEach

Misc



There may be some reasoning you had which I'm missing but I did't see the point in accepting the second argument peak.



Rewrite






const perfectPrice = (prices) => ;


console.log("(test 1):", perfectPrice([7, 1, 5, 3, 6, 4]))
console.log("(test 2):", perfectPrice([7, 6, 4, 3, 1]))
console.log("(test 3):", perfectPrice([7, 1, 5, 3, 6, 4]))
console.log("(test 4):", perfectPrice([1, 2]))
console.log("(test 5):", perfectPrice([7, 1, 5, 3, 6, 4]))
console.log("(test 6):", perfectPrice([2, 9, 5, 3, 1, 4]))








share|improve this answer





















    Your Answer




    StackExchange.ifUsing("editor", function ()
    return StackExchange.using("mathjaxEditing", function ()
    StackExchange.MarkdownEditor.creationCallbacks.add(function (editor, postfix)
    StackExchange.mathjaxEditing.prepareWmdForMathJax(editor, postfix, [["\$", "\$"]]);
    );
    );
    , "mathjax-editing");

    StackExchange.ifUsing("editor", function ()
    StackExchange.using("externalEditor", function ()
    StackExchange.using("snippets", function ()
    StackExchange.snippets.init();
    );
    );
    , "code-snippets");

    StackExchange.ready(function()
    var channelOptions =
    tags: "".split(" "),
    id: "196"
    ;
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function()
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled)
    StackExchange.using("snippets", function()
    createEditor();
    );

    else
    createEditor();

    );

    function createEditor()
    StackExchange.prepareEditor(
    heartbeatType: 'answer',
    convertImagesToLinks: false,
    noModals: false,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: null,
    bindNavPrevention: true,
    postfix: "",
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    );



    );








     

    draft saved


    draft discarded


















    StackExchange.ready(
    function ()
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f200706%2fbuy-and-sell-a-stock-for-maximum-profit-given-a-day-and-a-price%23new-answer', 'question_page');

    );

    Post as a guest






























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes








    up vote
    0
    down vote













    Readability



    • The way you've named your variables makes the code more difficult to read for example peak just doesn't make sense to me. Another consideration would be to rename buy_day to cheapest_day

    • Don't overcomplicate things: I found the return statement at the end of your forEach confusing

    General syntax improvement that would make the code easier to read:



    • Use camelCase over snake_case

    • Use dot notation when accessing an objects properties where possible

    Remove unnecessary/unused code



    • You have an if/elseif that does the same thing this can be simplified using an or statement if (this || that)


    • peak.sell and peak.sell_day are never used, same for all in your prices.forEach

    Misc



    There may be some reasoning you had which I'm missing but I did't see the point in accepting the second argument peak.



    Rewrite






    const perfectPrice = (prices) => ;


    console.log("(test 1):", perfectPrice([7, 1, 5, 3, 6, 4]))
    console.log("(test 2):", perfectPrice([7, 6, 4, 3, 1]))
    console.log("(test 3):", perfectPrice([7, 1, 5, 3, 6, 4]))
    console.log("(test 4):", perfectPrice([1, 2]))
    console.log("(test 5):", perfectPrice([7, 1, 5, 3, 6, 4]))
    console.log("(test 6):", perfectPrice([2, 9, 5, 3, 1, 4]))








    share|improve this answer

























      up vote
      0
      down vote













      Readability



      • The way you've named your variables makes the code more difficult to read for example peak just doesn't make sense to me. Another consideration would be to rename buy_day to cheapest_day

      • Don't overcomplicate things: I found the return statement at the end of your forEach confusing

      General syntax improvement that would make the code easier to read:



      • Use camelCase over snake_case

      • Use dot notation when accessing an objects properties where possible

      Remove unnecessary/unused code



      • You have an if/elseif that does the same thing this can be simplified using an or statement if (this || that)


      • peak.sell and peak.sell_day are never used, same for all in your prices.forEach

      Misc



      There may be some reasoning you had which I'm missing but I did't see the point in accepting the second argument peak.



      Rewrite






      const perfectPrice = (prices) => ;


      console.log("(test 1):", perfectPrice([7, 1, 5, 3, 6, 4]))
      console.log("(test 2):", perfectPrice([7, 6, 4, 3, 1]))
      console.log("(test 3):", perfectPrice([7, 1, 5, 3, 6, 4]))
      console.log("(test 4):", perfectPrice([1, 2]))
      console.log("(test 5):", perfectPrice([7, 1, 5, 3, 6, 4]))
      console.log("(test 6):", perfectPrice([2, 9, 5, 3, 1, 4]))








      share|improve this answer























        up vote
        0
        down vote










        up vote
        0
        down vote









        Readability



        • The way you've named your variables makes the code more difficult to read for example peak just doesn't make sense to me. Another consideration would be to rename buy_day to cheapest_day

        • Don't overcomplicate things: I found the return statement at the end of your forEach confusing

        General syntax improvement that would make the code easier to read:



        • Use camelCase over snake_case

        • Use dot notation when accessing an objects properties where possible

        Remove unnecessary/unused code



        • You have an if/elseif that does the same thing this can be simplified using an or statement if (this || that)


        • peak.sell and peak.sell_day are never used, same for all in your prices.forEach

        Misc



        There may be some reasoning you had which I'm missing but I did't see the point in accepting the second argument peak.



        Rewrite






        const perfectPrice = (prices) => ;


        console.log("(test 1):", perfectPrice([7, 1, 5, 3, 6, 4]))
        console.log("(test 2):", perfectPrice([7, 6, 4, 3, 1]))
        console.log("(test 3):", perfectPrice([7, 1, 5, 3, 6, 4]))
        console.log("(test 4):", perfectPrice([1, 2]))
        console.log("(test 5):", perfectPrice([7, 1, 5, 3, 6, 4]))
        console.log("(test 6):", perfectPrice([2, 9, 5, 3, 1, 4]))








        share|improve this answer













        Readability



        • The way you've named your variables makes the code more difficult to read for example peak just doesn't make sense to me. Another consideration would be to rename buy_day to cheapest_day

        • Don't overcomplicate things: I found the return statement at the end of your forEach confusing

        General syntax improvement that would make the code easier to read:



        • Use camelCase over snake_case

        • Use dot notation when accessing an objects properties where possible

        Remove unnecessary/unused code



        • You have an if/elseif that does the same thing this can be simplified using an or statement if (this || that)


        • peak.sell and peak.sell_day are never used, same for all in your prices.forEach

        Misc



        There may be some reasoning you had which I'm missing but I did't see the point in accepting the second argument peak.



        Rewrite






        const perfectPrice = (prices) => ;


        console.log("(test 1):", perfectPrice([7, 1, 5, 3, 6, 4]))
        console.log("(test 2):", perfectPrice([7, 6, 4, 3, 1]))
        console.log("(test 3):", perfectPrice([7, 1, 5, 3, 6, 4]))
        console.log("(test 4):", perfectPrice([1, 2]))
        console.log("(test 5):", perfectPrice([7, 1, 5, 3, 6, 4]))
        console.log("(test 6):", perfectPrice([2, 9, 5, 3, 1, 4]))








        const perfectPrice = (prices) => ;


        console.log("(test 1):", perfectPrice([7, 1, 5, 3, 6, 4]))
        console.log("(test 2):", perfectPrice([7, 6, 4, 3, 1]))
        console.log("(test 3):", perfectPrice([7, 1, 5, 3, 6, 4]))
        console.log("(test 4):", perfectPrice([1, 2]))
        console.log("(test 5):", perfectPrice([7, 1, 5, 3, 6, 4]))
        console.log("(test 6):", perfectPrice([2, 9, 5, 3, 1, 4]))





        const perfectPrice = (prices) => ;


        console.log("(test 1):", perfectPrice([7, 1, 5, 3, 6, 4]))
        console.log("(test 2):", perfectPrice([7, 6, 4, 3, 1]))
        console.log("(test 3):", perfectPrice([7, 1, 5, 3, 6, 4]))
        console.log("(test 4):", perfectPrice([1, 2]))
        console.log("(test 5):", perfectPrice([7, 1, 5, 3, 6, 4]))
        console.log("(test 6):", perfectPrice([2, 9, 5, 3, 1, 4]))






        share|improve this answer













        share|improve this answer



        share|improve this answer











        answered 2 hours ago









        mrmadhat

        212




        212






















             

            draft saved


            draft discarded


























             


            draft saved


            draft discarded














            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f200706%2fbuy-and-sell-a-stock-for-maximum-profit-given-a-day-and-a-price%23new-answer', 'question_page');

            );

            Post as a guest













































































            Popular posts from this blog

            Greedy Best First Search implementation in Rust

            Function to Return a JSON Like Objects Using VBA Collections and Arrays

            C++11 CLH Lock Implementation