动态规划——买股票的问题

今天是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;                     } }

原文地址:https://www.cnblogs.com/maowuyu-xb/p/6249259.html