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

  • 相关阅读:
    js联系题目
    js运算符
    太极图
    第一周 Welcome
    对 vscode 自动格式化的结果不太满意,我们该如何自己调整直至自己满意为止
    ASP.NET MVC5.0 OutputCache不起效果
    对照实验(1)-批量清理系统临时文件
    ES6
    19.局部变量和全局变量
    18.函数定义和参数
  • 原文地址:https://www.cnblogs.com/maowuyu-xb/p/6249259.html
Copyright © 2011-2022 走看看