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 }
  • 相关阅读:
    STM32 HAL库 UART 串口读写功能笔记
    c语言数组越界的避免方法
    MOS管做开关之初理解
    keil mdk 菜单 “project” 崩溃问题解决
    51 arm x86 的大小端记录
    (C99)复合字面量
    如何的keil试试调试中,看逻辑分析仪Logic viwer
    c语言之——整型的隐式转换与溢出检测
    C语言入坑指南-缓冲区溢出
    C语言入坑指南-被遗忘的初始化
  • 原文地址:https://www.cnblogs.com/reynold-lei/p/3313808.html
Copyright © 2011-2022 走看看