`

leetcode : Best Time to Buy and Sell Stock

 
阅读更多

 

最近看到网站上提到了leetcode网站,用来在线面试算法;就上去看了下,自己也解决了一题,蛮有意思的,偶尔做做算法练练脑。

题目Best Time to Buy and Sell Stock

 

Say you have an array for which the ith element is the price of a given stock on day i.

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

 

大致的意思就是输入一个股票的股价数组,第i个元素代表第i天的股价,只允许买入卖出一次,问最大的利润是多少?

 

 

第一个反映和解决:

两层for循环遍历下即可,在浏览器中输入完成;提交"judge small"按钮,提示有非法字符;排除后,正确运行。代码如下:

 

public class Solution {
    public int maxProfit(int[] prices) {
        // Start typing your Java solution below
        // DO NOT write main() function
        
        //check the input
        if(prices==null||prices.length<=1){
            
            return 0;
        }
        
        
        //proces
        int max = 0;
        int buyPoint = 0;
        int sellPoint = 1;
        

        for (int j=0;j<prices.length -1;j++){
            buyPoint = j;
            for (int i=j+1;i<prices.length;i++){
                sellPoint = i;
                if (prices[i]-prices[j]>max){
                    max = prices[i]-prices[j];
                    sellPoint = i;
                }
            }
        }
        
        
        
        // not buy 
        if (max<0){
            return 0;
        }
        
        return max;
        
    }
}

 

 

但是当按"judge large"时,提示 运行超时:(

 

第二解决:

思考了下 o(N平方),能不能降到N(log N),花了大概5分钟思考和验证(算法知识已经遗忘了很多),居然找出了o(N)的算法:

1先找出股价最小值和股价最大值的位置,

1.1如果股价最小点的位置在股价最大值的位置之前,直接输出最大值和最小值的差,程序结束;

1.2 反之,三段式处理。

2,三段式处理:

2.1 从数组开始点到“股价最大值的位置”这一区间,只要找到这一段的最小值,然后和之前的最大值相减,就是这段可能的最大利润;P1

2.2 从"股价最小点的位置"到数组的结尾这一区间,只要找到这一段的最大值,冉舟和之前的最小值相减,就是这一段可能的最大李瑞:P3

2.3“股价最大值的位置”到"股价最小点的位置"这一区间,这段区间为止,递归解决;P2

 

编程好程序,再执行,还是提示超时。。。这个算法的的复杂度是O(N)啊,应该不可能有再快的算法了。突然想到java对递归支持不好,如果数据很长的话,可能StackOverFlow。

 

最终版本:

那就改成非递归的版本吧,改完再测试,果然ok了。

代码如下:

 

public class Solution {
    public int maxProfit(int[] prices) {
        // Start typing your Java solution below
        // DO NOT write main() function
        
        //check the input
        if(prices==null||prices.length<=1){
            return 0;
        }
    
           
        int start = 0;
        int end = prices.length-1;
        int max = 0;
        
        
        while (end - start >=1){
            //find the smallest and biggest
            int smallest = prices[start];
            int sPoint = start;
            int biggest = prices[start];
            int bPoint = start;
            for (int i=start+1;i<=end;i++){
                if (prices[i]<smallest){
                    smallest = prices[i];
                    sPoint = i;
                }
                
                if (prices[i]>biggest){
                    biggest = prices[i];
                    bPoint = i;
                }
                
            }
    
            if (sPoint<bPoint){
                if (biggest-smallest>max){
                    max = biggest - smallest;
                } 
                break;          
            }
            
            
            // find the smallest in the interval
            int p1 = 0;
            int s1 = biggest;
            for (int i=start;i<bPoint;i++){
                if (prices[i]<s1){
                    s1 = prices[i];
                }
            }
            p1 = biggest -s1;
            if (p1>max){
                max = p1;
            }
            
            
            // find the smallest in the third interval        
            int p3 = 0;
            int b1 = smallest;
            for (int i=sPoint+1;i<=end;i++){
                if (prices[i]>b1){
                    b1 = prices[i];
                }
            }
            p3 = b1 - smallest;
    
            if (p3>max){
                max = p3;
            }
             
            //find the smallest in the second interval
            start = bPoint+1;
            end = sPoint-1;

        }
        


        // not buy 
        if (max<0){
            return 0;
        }
        
        return max;
        
    }
            
    
}

 

 

 

 

小结:

1)使用在线文本编辑器后,才知道Eclipse的好啊,一些无聊的错误在eclipse中根本就不会发生,而且如果有问题,直接输入异常,真的不行debug下就知道原因了;

2)leetcode网站的题目质量还是很高的;

3)这种方式的面试确实对动手能力要求很高(类ACM),而且能绕过一些麻烦的环境准备问题,对面试过程确实有帮助。

 

 

分享到:
评论
2 楼 wtnbmy_aaaeau 2015-08-04  
class Solution {
public:
    int maxProfit(vector<int>& prices) {

        int num_days = prices.size();
        if(num_days == 0) {
            return 0;
        }

        int max_profit = 0;
        int lowest_price = prices[0];

        for(int i=1; i<num_days; i++) {

            int profit_tmp = prices[i]-lowest_price;
            if(profit_tmp > max_profit) {
                max_profit = profit_tmp;
            }

            if(prices[i] < lowest_price) {
                lowest_price = prices[i];
            }
        }

        return max_profit;
    }
};
1 楼 花与剑 2014-06-21  
兄台,你这个非递归的程序算法的复杂度不是o(N).Bad 的 情况是O(N^2)
比如:
64,32,16,8,4,2,1.
复杂度是
o(7)+o(5)+o(3)+o(1) = 16

相关推荐

    leetcode题目:Best Time to Buy and Sell Stock II

    leetcode题目:Best Time to Buy and Sell Stock II

    lrucacheleetcode-LeetCode:CppSourceCode的LeetCode解决方案

    leetcode LeetCode 解决题目的总数: 136/1753 微信公众号: 工程师Ruojhen 算法-动态规划 题号 名称 English Name 题解 53 最大子序和 Maximum Subarray 70 爬楼梯 Climbing Stairs 121 买卖股票的最佳时机 Best Time...

    股票收益leetcode-leetcode:leetcode摘要

    股票收益leetcode LeetCode 股票问题 Best Time to Buy and Sell Stock (Easy) 一次交易,找最大收益 for i in prices: low = min(low, i) profit = max(profit, i-low) Best Time to Buy and Sell Stock II (Easy) ...

    javalruleetcode-leetcode-java:力码笔记

    leetcode leetcode-java leetcode刷题笔记 已做题目列表 1.Two Sum 3.Longest Substring Without Repeating Characters 5.Longest Palindromic Substring 20.Valid Parentheses 26.Remove Duplicates from Sorted ...

    leetcode分类-LeetCode:力码

    leetcode 分类 LeetCode LeetCode Java Solution 2018年5月31日 更新 最近刷了一遍 LeetCode,发现第一次的代码确实有些 low 很多代码并不简洁,本来1行的代码可以写成3行 思维混乱 没有按照题目类型分类 没有写结题...

    LeetCode:LeetCode Java解决方案

    公众号 coding 笔记、点滴记录,以后的文章也会...最近花时间分门别类整理了 LeetCode 的前 500 题,把相似的题目都放在了一起,比如Best Time to Buy and Sell Stock的6道题,这些题目放在一起刷效果更好。 简书博客:

    Andy619-Zhu#CS-Notes-chu#63. 股票的最大利润1

    63. 股票的最大利润题目链接Leetcode:121. Best Time to Buy and Sell Stock题目描述可以有一次买入和一次卖出,买入必

    leetcode卡-leetcode:利特码解决方案

    leetcode卡 leetcode exercises 3-5 solutions everyday. fighting~ TODO array Best Time to Buy and Sell Stock II Valid Sudoku linked list Palindrome linked list Linked List Cycle trees Convert Sorted ...

    LeetCode:Leetcode-解决方案

    Best Time to Buy and Sell Stock [121]3. Climbing Stairs [70]4. Maximum Subarray [53]5. House Robber [198]6. Range Sum Query - Immutable [303]7. Counting Bits [338]8. Palindromic Substrings [647]9. ...

    leetcode-leetcode:leetcode的最佳C++解决方案

    leetcode leetcode The optimum C++ solutions for the leetcode 这是我自己写的leetcode的题解,目前已经完成了70%左右,后续部分会很快更新 这里放上来的代码都能保证是最优解(复杂度最优) 当然有些题目因为测试...

    leetcode小岛出水口-leetcode:leetcode训练

    leetcode小岛出水口 leetcode training one problem on file 为了方便文档管理,项目逐渐文档化,以单个文件作为集合最小集。 go语言不能完全适合写算法题 后续会尽可能加入rust或者c的题解 清单 0965. Univalued ...

    LeetCode:LeetCode题解

    Best_Time_To_Buy_And_Sell_Stock Java 简单的 122 Best_Time_To_Buy_And_Sell_StockII Java 简单的 125 Valid_Palindrome Java 简单的 136 单号 Java 简单的 137 Single_NumberII Java 中等的 167 Two_...

    leetcode中文版-leetcode:leetcode

    leetcode中文版车鸟 一组用python编写的算法。 种类 ...best_time_to_buy_and_sell_stock_II binary_tree_inorder_traversal binary_tree_level_order_traversal binary_tree_level_order_traversal_I

    javalruleetcode-leetcode:更多信息请访问Gitbook:https://wentao-shao.gitbook.io/

    Best Time To Buy And Sell Stock [Binary Tree](Basic-Knowledge/Binary tree.md) Serialize And Deserialize Bit 1.position 2.sequence Sell Stock 区间型 矩阵坐标 Word Ladder Add Two Numbers Matrix Spiral ...

    股票买卖最佳时机leetcode-best-time-to-buy-and-sell-stock:让我们弄清楚什么时候买一些股票!这不应该在现

    股票买卖最佳时机leetcode GitFitCode 配对编码挑战! 买卖股票的最佳时机 让我们弄清楚什么时候买一些股票! 这不应该在现实生活中使用。 现在不管你认为你的算法有多好:)。 我确实鼓励您选择一只您感兴趣的股票,...

    Leetcode的ac是什么意思-LeetCodeInJava:leetcode-java

    Leetcode的ac是什么意思 LeetCodeInJava List #98 Validate Binary Search Tree #100 Same Tree #104 Maximum Depth of Binary Tree #122 Best Time to Buy and Sell Stock II #136 Single Number #150 Evaluate ...

    cpp-算法精粹

    Best Time to Buy and Sell Stock with Cooldown Interleaving String Scramble String Minimum Path Sum Edit Distance Decode Ways Distinct Subsequences Word Break Word Break II Dungeon Game House Robber ...

    leetcode答案-LeetCode-Trip:LeetCode刷题代码,大佬勿入

    leetcode 答案 LeetCode-Trip LeetCode刷题代码,大佬勿入。 为一年后的研究生找工作准备 目标是BAT的算法岗哈哈哈哈哈 争取做到每日一更 嗯…… 19.10.22:鸽了这么久,我又回来了……主要在实验室天天没啥事,过于...

    leetcode浇花-LCSolutions:我的力扣解决方案

    leetcode 浇花力扣解决方案 简单的 #0001 - Two Sum #0007 - Reverse Integer #0009 - Palindrome Number #0035 - Search Insert Position #0058 - Length of Last Word #0066 - Plus One #0083 - Remove Duplicates...

    lrucacheleetcode-LeetCode_30Day:力扣30天挑战赛

    lru缓存leetcode 力扣_30天 力扣 30 天挑战赛 日 问题描述 问题和解决方案链接 Git 解决方案页面 1 SINGLE NUMBER 2 HAPPY NUMBER 3 MAXIMUM SUBARRAY 4 Move Zeroes 5 Best Time to Buy and Sell Stock II 6 GROUP ...

Global site tag (gtag.js) - Google Analytics