zoukankan      html  css  js  c++  java
  • 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.

    最简单的方法就是穷举,O(n2)。

     1 public class Solution {
     2     public int maxProfit(int[] prices) {
     3         // Start typing your Java solution below
     4         // DO NOT write main() function
     5         int max = 0;
     6         for(int i = 0; i < prices.length; i ++){
     7             for(int j = i + 1; j <  prices.length; j ++){
     8                 int cur = prices[j] - prices[i];
     9                 if(cur > max) max = cur;
    10             }
    11         }
    12         return max;
    13     }
    14 }

    这题有O(n)算法。 使用额外的prices.length空间。 存入从后往前n个数里最大的数。 这样就不用双层循环了。

     1 public class Solution {
     2     public int maxProfit(int[] prices) {
     3         // Start typing your Java solution below
     4         // DO NOT write main() function
     5         int max = 0;
     6         int maxnum[] = new int[prices.length];
     7         if(prices.length == 0) return 0;
     8         if(prices.length == 1) return 0;
     9         maxnum[prices.length - 1] = prices[prices.length - 1];
    10         for(int i = prices.length - 2; i > -1; i --){
    11             if(prices[i] > maxnum[i + 1]) maxnum[i] = prices[i];
    12             else maxnum[i] = maxnum[i + 1];
    13         }
    14         for(int i = 0; i < prices.length-1; i ++){
    15             if(maxnum[i+1] - prices[i] > max)max =  maxnum[i+1] - prices[i]; 
    16         }
    17         return max;
    18     }
    19 }

     第二遍:

     1 public class Solution {
     2     public int maxProfit(int[] prices) {
     3         // IMPORTANT: Please reset any member data you declared, as
     4         // the same Solution instance will be reused for each test case.
     5         int max = 0;
     6         if(prices.length == 0)return 0;
     7         int highest = 0;
     8         for(int i = prices.length - 1; i > 0; i --){
     9             highest = Math.max(prices[i],highest);
    10             int cur = highest - prices[i - 1];
    11             if(cur > max) max = cur;
    12         }
    13         return max;
    14     }
    15 }
  • 相关阅读:
    Golang (Go语言) Mac OS X下环境搭建 环境变量配置 开发工具配置 Sublime Text 2
    网站状态保存方法
    学习MVC第一课:初识MVC
    ASP.NET MVC 中动态从路由中获取URL
    ASP.NET MVC2程序开发入门到精通系列课程01
    OpenCV 里的sigma 是多少
    日期大小比较
    安装完ODAC,出现ORA12560:TNS:协议适配器错误
    Spring+IBATIS+Struts2开发流程
    【转】SSH标准配置
  • 原文地址:https://www.cnblogs.com/reynold-lei/p/3313808.html
Copyright © 2011-2022 走看看