zoukankan      html  css  js  c++  java
  • 动态规划——买股票的问题

    今天是2017年1月4号,中午13点整躺在宿舍床上。。。我居然睡不着,,闭着眼睛三个小时,仍旧没有睡着 。。。。唉   还是起来写个算法

    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

    法一)最笨的循环问题,从头到尾的遍历,假设当前指针对应的数为A,找出位于A后面序列中的最大数为B,B-A作为结果,存储在结果序列中result【i】

    public class Solution {       

    public int  findMax(int start,int a[]){       

      int temp=0;        

    temp=a[start];        

    for(int i=start+1;i<a.length;i++)        

    if(a[i]>temp)          

    temp=a[i];        

    return temp;          }

        public int maxProfit(int[] prices) {              

       int result[100];        

    int maxProfit=0;        

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

      int m=prices[j];       

      int n=findMax(j,prices);       

      if (n-m>0)        

    result[j]=n-m;     

        else       

      result[j]=0;       

      }        

    maxProfit=findMax(0,result);        

    return maxProfit;                     } }

  • 相关阅读:
    针对web高并发量的处理
    外边距合并,外边距折叠
    cookie 和session 的区别:
    ng-if ng-show ng-hide 的区别
    JavaScript中的arguments,callee,caller
    git常见命令
    jQuery中.bind() .live() .delegate() .on()的区别
    为什么要使用sass
    js兼容性记录
    poj1004
  • 原文地址:https://www.cnblogs.com/maowuyu-xb/p/6249259.html
Copyright © 2011-2022 走看看