码迷,mamicode.com
首页 > 其他好文 > 详细

121.Best Time to Buy and Sell Stock

时间:2015-02-12 22:51:58      阅读:178      评论:0      收藏:0      [点我收藏+]

标签:

Say you have an array for which the ith element isthe price of a given stock on day i.

If you were only permitted to complete at most one transaction (ie, buyone and sell one share of the stock), design an algorithm to find the maximumprofit.

HideTags

 Array Dynamic Programming



#pragma once
#include<iostream>
#include<vector>
using namespace std;

/*i+1 减去i ,构造每天盈利数组,求子数组最大和*/

//求子数组最大和,若和为负,应返回0
int findMax(int *list, int n)
{
	int maxsum = 0;//初始设为0,可保证最后返回大于等于0
	int sum = 0;
	for (int i = 0; i < n;i++)
	{
		sum += list[i];
		if (sum > maxsum)
			maxsum = sum;
		else
			if (sum <= 0)
				sum = 0;
	}
	return maxsum;
}

int maxProfit(vector<int> &prices) 
{
	if (prices.size() == 0)
		return 0;
	int *list = new int[prices.size() - 1];
	for (int i = 0; i < prices.size() - 1; i++)
		list[i] = prices[i + 1] - prices[i];
	return findMax(list, prices.size() - 1);
}

void main()
{
	
	system("pause");
}

 

 

121.Best Time to Buy and Sell Stock

标签:

原文地址:http://blog.csdn.net/hgqqtql/article/details/43767829

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!