(1)Best Time to Buy and Sell Stock

Total Accepted: 10430 Total Submissions: 33800My Submissions

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.

url:http://oj.leetcode.com/problems/best-time-to-buy-and-sell-stock/

测试用例

空数组:  []

只有一个元素的数组: [1]

所有收益均为负数的数组: [8,7,4,2]

这一题,首先使用的是暴力办法,中间做了一些局部优化,但是总体复杂度仍然是O(n2),于是乎,妥妥的Time Limit Exceeded,下面是暴力代码

public int maxProfit(int[] prices){

        

        int i,j,max,temp,holda,holdb;

        if(prices.length==0 || prices.length==1){

            return 0;

        }

        temp = prices[0];

        max = prices[1]-prices[0];

        for(i=0;i<prices.length-1;i++){

            if(prices[i]<temp){

                temp = prices[i];

                for(j=i;j<prices.length;j++){

                    if(prices[j]-prices[i]>max){

                        max = prices[j]-prices[i];

                        holda = i;

                        holdb = j;

                    }

                }

            }

            

        }

        return max;

    }

既然TLE了,于是乎,就去想办法了。

可以得到如果本月买入,下个卖出能够得到的收益,然后股票的最大收益问题就变成了一个已知int数组的最大和子串问题。而这个问题本身有很成熟的解决方案:暴力循环--》O(n2),递归--》O(nlgn),动态规划--》O(n) 都可以解决。

/*复杂度:O(n):accpt*/

public class Solution {

        public int maxProfit(int[] prices){

        

        int temp = 0;

        int max = 0;

        int[] det = new int[prices.length];

        for(int i=0;i<prices.length-1;i++){

            det[i] = prices[i+1]-prices[i];

        }

        for(int i=0;i<det.length;i++){

            temp = temp + det[i];

            if(temp < 0){

                temp = 0;

            }

            if(temp > max){

                max = temp;

            }

        }

        return max;

    }

}

本题也可以使用下面一题里面的思路,求出所有波段的profit值,在过程中记录获利最大的一个波段,复杂度同样为O(n)。

(2)Best Time to Buy and Sell Stock II

Total Accepted: 10315 Total Submissions: 29085My SubmissionsSay you have an array for which the ith element is the price of a given stock on day i.

Design an algorithm to find the maximum profit. You may complete as many transactions as you like (ie, buy one and sell one share of the stock multiple times). However, you may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).

url:http://oj.leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/

测试用例:

空数组:  []

只有一个元素的数组: [1]

所有收益均为负数的数组: [8,7,4,2]

算法:周期性检查波底和封顶的值,profit=prices[封顶]-price[波底];直到数组全部元素都结束,注意点主要是边界值不能越界。

/*算法复杂度:O(n)*/

public class Solution {

    public int maxProfit(int[] prices) {

 

        int profit = 0;

        int minPos = 0;

        int maxPos = 0;

 

        while (maxPos < prices.length-1) {

            minPos = findMin(prices, maxPos);

            maxPos = findMax(prices, minPos);

            profit = profit +( prices[maxPos] - prices[minPos]);

        }

        return profit;

    }

 

    public int findMax(int[] prices, int pos) {

        int i;

        for(i=pos;i<prices.length-1 && prices[i+1]>=prices[i];i++){

        }

        return i;

    }

 

    public int findMin(int[] prices, int pos) {

        int i;

        for(i=pos;i<prices.length-1 && prices[i+1]<=prices[i];i++){

        }

        return i;

    }

}

leetcode刷题笔记的更多相关文章

  1. LeetCode刷题笔记和想法(C++)

    主要用于记录在LeetCode刷题的过程中学习到的一些思想和自己的想法,希望通过leetcode提升自己的编程素养 :p 高效leetcode刷题小诀窍(这只是目前对我自己而言的小方法,之后会根据自己 ...

  2. 18.9.10 LeetCode刷题笔记

    本人算法还是比较菜的,因此大部分在刷基础题,高手勿喷 选择Python进行刷题,因为坑少,所以不太想用CPP: 1.买股票的最佳时期2 给定一个数组,它的第 i 个元素是一支给定股票第 i 天的价格. ...

  3. LeetCode刷题笔记 - 12. 整数转罗马数字

    学好算法很重要,然后要学好算法,大量的练习是必不可少的,LeetCode是我经常去的一个刷题网站,上面的题目非常详细,各个标签的题目都有,可以整体练习,本公众号后续会带大家做一做上面的算法题. 官方链 ...

  4. Leetcode刷题笔记(双指针)

    1.何为双指针 双指针主要用来遍历数组,两个指针指向不同的元素,从而协同完成任务.我们也可以类比这个概念,推广到多个数组的多个指针. 若两个指针指向同一数组,遍历方向相同且不会相交,可以称之为滑动窗口 ...

  5. LeetCode刷题笔记(1-9)

    LeetCode1-9 本文更多是作为一个习题笔记,没有太多讲解 1.两数之和 题目请点击链接 ↑ 最先想到暴力解法,直接双循环,但是这样复杂度为n平方 public int[] twoSum(int ...

  6. leetcode刷题笔记08 字符串转整数 (atoi)

    题目描述 实现 atoi,将字符串转为整数. 在找到第一个非空字符之前,需要移除掉字符串中的空格字符.如果第一个非空字符是正号或负号,选取该符号,并将其与后面尽可能多的连续的数字组合起来,这部分字符即 ...

  7. LeetCode刷题笔记-回溯法-分割回文串

    题目描述: 给定一个字符串 s,将 s 分割成一些子串,使每个子串都是回文串. 返回 s 所有可能的分割方案. 示例: 输入: "aab"输出:[ ["aa", ...

  8. leetcode刷题笔记231 2的幂

    题目描述: 给定一个整数,写一个函数来判断它是否是2的幂. 题目分析: 判断一个整数是不是2的幂,可根据二进制来分析.2的幂如2,4,8,等有一个特点: 二进制数首位为1,其他位为0,如2为10,4为 ...

  9. leetcode刷题笔记342 4的幂

    题目描述: 给定一个整数 (32位有符整数型),请写出一个函数来检验它是否是4的幂. 示例:当 num = 16 时 ,返回 true . 当 num = 5时,返回 false. 问题进阶:你能不使 ...

随机推荐

  1. ZOJ 3042 City Selection II 【序】【离散化】【数学】

    题意: 输入数据n,m.n代表工厂的数量,m代表城市的数量. 接下来n+m行为工厂和城市的坐标. 规定如图所示方向刮风,工厂的air会污染风向地区的air. 注意,工厂和城市的坐标表示的是从x到x+1 ...

  2. Regional Changchun Online--Alisha’s Party

    Alisha's Party Time Limit: 3000/2000 MS (Java/Others)    Memory Limit: 131072/131072 K (Java/Others) ...

  3. linux tar 命令 --致力于“一眼看懂,随手就用”的随笔

    基本玩法: 压缩: tar -czf txt.tar.gz *.txt // 将当前目录下的所有txt文件,创建一个tar包,并用gzip算法,压缩成txt.tar.gz 文件 解压: tar -xz ...

  4. CODESOFT中线条形状该如何绘制

    CODESOFT条码设计软件提供了一系列工具,可帮助您设计完美的标签.在CODESOFT进行标签设计时,经常会需要创建除条码,文本对象除外的一些对象,那就是形状对象.如线条.圆形.矩形等.通过下面的示 ...

  5. C#调用C dll,结构体传参

    去年用wpf弄了个航线规划软件,用于生成无人机喷洒农药的作业航线,里面包含了不少算法.年后这几天将其中的算法移植到C,以便其他同事调用.昨天在用C#调用生成的dll时,遇到一些问题,折腾了好久才解决. ...

  6. 翻译「C++ Rvalue References Explained」C++右值引用详解 Part8:Perfect Forwarding(完美转发):解决方案

    本文为第八部分,目录请参阅概述部分:http://www.cnblogs.com/harrywong/p/cpp-rvalue-references-explained-introduction.ht ...

  7. OpenGL ES学习笔记(一)——基本用法、绘制流程与着色器编译

    首先声明下,本文为笔者学习<OpenGL ES应用开发实践指南(Android卷)>的笔记,涉及的代码均出自原书,如有需要,请到原书指定源码地址下载. 在Android.iOS等移动平台上 ...

  8. startup毕业论文

    今天起得相对比较晚,为的是一个没有目的面试,去了的结果.只是打击一下自己的自信心,走的时候,面试官冷冷的说了一句,你的面试到此结束,是的,我并没有很伤心,在门外等面试的时候,我就非常的后悔,今天是不该 ...

  9. yii中的若干问题

    一直觉得”程序猿“是个很细致的工作,就像绣花一样,一不小心缝错一针,就可能是个很大的bug,但是为什么平时看起来大而化之的男同胞们确能在这方面如此care呢?? 以下进入正文,省去华丽丽的词语,这里仅 ...

  10. asp.net中如何绑定combox下拉框数据(调用存储过程)

    #region 绑定类型(商品类型.仓库名称) public void DataType_Bind(int _peoid) { DataTable dt_goodsname = new DataTab ...