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 }
  • 相关阅读:
    进程间通信小结
    菜鸡和菜猫进行了一场Py交易
    菜鸡开始接触一些基本的算法逆向了
    菜鸡学逆向学得头皮发麻,终于它拿到了一段源代码
    静态分析-Windows找密码
    逆向-完成地址随机化关闭
    QSortFilterProxyModel 的过滤 排序
    linux命令2
    linux 命令1
    error c2059 c3905 c2148 c2238
  • 原文地址:https://www.cnblogs.com/reynold-lei/p/3313808.html
Copyright © 2011-2022 走看看