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;                     } }

  • 相关阅读:
    vue2.X对接高德地图:vue-amap(一)
    RequestHeaders添加自定义参数
    git 拉取远程分支到本地
    git输错密码怎么办?
    webstorm最新版破解
    flex布局
    call和apply区别
    localStorage,sessionStorage,cookie
    详解单页面路由的几种实现原理(附demo)
    微信的踩坑之路----微信分享title和icon不显示
  • 原文地址:https://www.cnblogs.com/maowuyu-xb/p/6249259.html
Copyright © 2011-2022 走看看