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 }
  • 相关阅读:
    U10783 名字被和谐了
    P1151 子数整数
    P2756 飞行员配对方案问题
    P3227 [HNOI2013]切糕
    BZOJ 2127: happiness(最小割解决集合划分)
    linux脚本初体验
    130902 周赛
    Citrix 服务器虚拟化之三十二 XenConvert
    数据字典统一管理,动态下拉框
    [置顶] oracle 数据库表中转换成java代码
  • 原文地址:https://www.cnblogs.com/reynold-lei/p/3313808.html
Copyright © 2011-2022 走看看